Skip to main content
Speech-to-text

Real-time speech recognition - Qwen

The real-time speech recognition service receives an audio stream and transcribes it into punctuated text in real time. Use it for live captioning, online meetings, voice chat, smart assistants, and similar scenarios.

Overview

The service streams audio and returns transcribed text with low latency.
  • Recognizes Mandarin Chinese with high accuracy, plus Cantonese, Sichuanese, and other dialects.
  • Handles complex acoustic environments, with automatic language detection and intelligent filtering of non-speech audio.
  • Recognizes a range of emotional states, including surprise, calm, happiness, sadness, disgust, anger, and fear.
  • Supports custom hotwords to improve recognition accuracy for specific terms.
  • Supports context enhancement to improve recognition accuracy by passing in conversation history or domain terms.
  • Outputs timestamps to produce structured recognition results.
  • Accepts flexible sample rates and multiple audio formats to fit different recording environments.
For batch scenarios such as meeting transcription, call analysis, and subtitle generation, use Non-real-time speech recognition. For guidance on choosing a model, see Speech-to-text.

Prerequisites

Quick start

The following examples show how to call the real-time speech recognition service through the DashScope SDK.
  • Qwen-Audio-3.0-ASR-Flash-Streaming/ Fun-ASR -Realtime
  • Qwen3-ASR-Flash-Realtime
  • Paraformer
In addition to WebSocket, this model also supports the AOQ protocol. For client-side integration that prioritizes stable latency, resilience on weak networks, and built-in full-duplex noise suppression and echo cancellation, AOQ is recommended. For a protocol comparison, see Realtime API overview.
  • Recognize speech from a microphone
  • Recognize a local audio file
Recognize speech from a microphone and output text in real time, so words appear as the speaker talks.
  • Java
  • Python
import com.alibaba.dashscope.audio.asr.recognition.Recognition;
import com.alibaba.dashscope.audio.asr.recognition.RecognitionParam;
import com.alibaba.dashscope.audio.asr.recognition.RecognitionResult;
import com.alibaba.dashscope.common.ResultCallback;
import com.alibaba.dashscope.utils.Constants;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.TargetDataLine;

import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        // The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your real workspace ID. Configurations differ by region.
        Constants.baseWebsocketApiUrl = "wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference";
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(new RealtimeRecognitionTask());
        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.MINUTES);
        System.exit(0);
    }
}

class RealtimeRecognitionTask implements Runnable {
    @Override
    public void run() {
        RecognitionParam param = RecognitionParam.builder()
                .model("qwen-audio-3.0-asr-flash-streaming")
                // The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
                // If you have not configured the environment variable, replace the following line with your Model Studio API Key: .apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .format("pcm")
                .sampleRate(16000)
                .build();
        Recognition recognizer = new Recognition();

        ResultCallback<RecognitionResult> callback = new ResultCallback<RecognitionResult>() {
            @Override
            public void onEvent(RecognitionResult result) {
                if (result.isSentenceEnd()) {
                    System.out.println("Final Result: " + result.getSentence().getText());
                } else {
                    System.out.println("Intermediate Result: " + result.getSentence().getText());
                }
            }

            @Override
            public void onComplete() {
                System.out.println("Recognition complete");
            }

            @Override
            public void onError(Exception e) {
                System.out.println("RecognitionCallback error: " + e.getMessage());
            }
        };
        try {
            recognizer.call(param, callback);
            // Create the audio format
            AudioFormat audioFormat = new AudioFormat(16000, 16, 1, true, false);
            // Match the default recording device based on the format
            TargetDataLine targetDataLine =
                    AudioSystem.getTargetDataLine(audioFormat);
            targetDataLine.open(audioFormat);
            // Start recording
            targetDataLine.start();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            long start = System.currentTimeMillis();
            // Record for 50s and perform real-time transcription
            while (System.currentTimeMillis() - start < 50000) {
                int read = targetDataLine.read(buffer.array(), 0, buffer.capacity());
                if (read > 0) {
                    buffer.limit(read);
                    // Send the recorded audio data to the streaming recognition service
                    recognizer.sendAudioFrame(buffer);
                    buffer = ByteBuffer.allocate(1024);
                    // The recording rate is limited; sleep for a short while to prevent excessive CPU usage
                    Thread.sleep(20);
                }
            }
            recognizer.stop();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Close the WebSocket connection after the task is complete
            recognizer.getDuplexApi().close(1000, "bye");
        }

        System.out.println(
                "[Metric] requestId: "
                        + recognizer.getLastRequestId()
                        + ", first package delay ms: "
                        + recognizer.getFirstPackageDelay()
                        + ", last package delay ms: "
                        + recognizer.getLastPackageDelay());
    }
}

Recognition configuration

Qwen3-ASR-Flash-Realtime interaction modes

The Qwen3-ASR-Flash-Realtime Realtime API offers two interaction modes:
  • VAD mode (default): The server automatically detects the start and end of speech (segmentation). This mode suits real-time conversations, meeting notes, and similar scenarios. To enable it, configure the session.turn_detection parameter (enabled by default).
  • Manual mode: The client controls segmentation by sending input_audio_buffer.commit. This mode suits scenarios that require explicit control over when audio is sent, such as sending a voice message in a chat app. To enable it, set session.turn_detection to null.
Switch interaction modes:
  • WebSocket: Set the turn_detection field in a session.update event.
{
    "type": "session.update",
    "session": {
        "turn_detection": null
    }
}
  • Python SDK: Set the enable_turn_detection parameter in the update_session method.
conversation.update_session(
    enable_turn_detection=False
)
  • Java SDK: Set the enableTurnDetection parameter through OmniRealtimeConfig.builder().
OmniRealtimeConfig config = OmniRealtimeConfig.builder()
        .enableTurnDetection(false)
        .build();
conversation.updateSession(config);
For complete SDK code examples, see Qwen-ASR-Realtime Python SDK - API reference and Java SDK. For the WebSocket event lifecycle, see Event interaction flow.

VAD segmentation configuration

Voice Activity Detection (VAD) determines when a continuous segment of speech ends, which triggers the final recognition result event. All three model families enable server-side VAD by default, but their parameter names and tuning granularity differ:
  • Qwen-Audio-3.0-ASR-Flash-Streaming / Fun-ASR-Realtime / Paraformer: Configured through max_sentence_silence (the VAD silence threshold for segmentation, in milliseconds). When the silence after a segment of speech exceeds this threshold, the system treats the sentence as complete.
  • Qwen3-ASR-Flash-Realtime: Configured through session.turn_detection, which includes silence_duration_ms (the silence duration threshold that ends a turn when exceeded; server default 800, with 400 recommended for conversation and chat scenarios that need fast segmentation) and threshold (VAD detection sensitivity; server default 0.2). Qwen3-ASR-Flash-Realtime also supports Manual mode, which disables VAD and uses client-side commit for segmentation. For details, see Qwen3-ASR-Flash-Realtime interaction modes above.
Parameter names vary by protocol: the same concept is called max_sentence_silence in Qwen-Audio-3.0-ASR-Flash-Streaming / Fun-ASR-Realtime / Paraformer, and silence_duration_ms in Qwen3-ASR-Flash-Realtime. For the full field definitions, see API reference.

Advanced features

Improve accuracy with hotwords

Use hotwords to improve recognition accuracy for specific terms, such as brand names, personal names, and proper terminology. For detailed hotword configuration and usage, see Improve recognition accuracy.

Improve accuracy with context enhancement

Context enhancement passes conversation history or domain terminology to the ASR model to significantly improve transcription accuracy for proper terms. For detailed usage and result examples, see Context enhancement.

Get timestamps

The Qwen-Audio-3.0-ASR-Flash-Streaming, Fun-ASR-Realtime, and Paraformer model families output timestamps at both the sentence level and the word level by default, which supports subtitle alignment, keyword highlighting, karaoke-style read-along, and similar scenarios. Qwen3-ASR-Flash-Realtime (qwen3-asr-flash-realtime) does not currently return timestamps. If you need timestamps, use Qwen-Audio-3.0-ASR-Flash-Streaming, Fun-ASR-Realtime, or Paraformer. For file transcription, the Qwen ASR recording-file transcription model qwen3-asr-flash-filetrans supports word-level timestamps. For details, see Non-real-time speech recognition. Timestamps are returned in milliseconds at two levels:
  • Sentence level: payload.output.sentence.begin_time and payload.output.sentence.end_time mark the start and end of a full sentence in the audio. In an intermediate result, end_time may be null and is filled with the final value when the sentence ends (sentence_end = true).
  • Word level: The payload.output.sentence.words array, where each element contains begin_time, end_time, text (the word or character text), and punctuation (the punctuation that follows the word, or an empty string if none).
The following excerpt shows the response structure:
{
  "payload": {
    "output": {
      "sentence": {
        "begin_time": 170,
        "end_time": 920,
        "text": "OK, I got it",
        "sentence_end": true,
        "words": [
          { "begin_time": 170, "end_time": 295, "text": "OK", "punctuation": "," },
          { "begin_time": 295, "end_time": 503, "text": "I", "punctuation": "" },
          { "begin_time": 503, "end_time": 711, "text": "got", "punctuation": "" },
          { "begin_time": 711, "end_time": 920, "text": "it", "punctuation": "" }
        ]
      }
    }
  }
}
The field names above follow the WebSocket JSON paths. Different SDKs expose these fields with their own naming conventions (dictionary keys, object properties, getter methods, and so on). For the complete field mapping, see the API reference for each SDK. For the full field definitions, see API reference.

Emotion recognition

Qwen3-ASR-Flash-Realtime and some Paraformer models can include the speaker's emotional state in the transcription result, but the two differ in output granularity and in how the feature is enabled. Qwen3-ASR-Flash-Realtime (qwen3-asr-flash-realtime): Always on, no configuration required. The emotion is returned through a top-level emotion field in both the conversation.item.input_audio_transcription.text and conversation.item.input_audio_transcription.completed events. The value is one of seven fine-grained emotions: surprised, neutral, happy, sad, disgusted, angry, and fearful.
{
  "type": "conversation.item.input_audio_transcription.text",
  "emotion": "neutral",
  "text": "The weather is nice today",
  "stash": ""
}
Paraformer (paraformer-realtime-8k-v2): This is the only Paraformer model that supports emotion recognition. The result is returned through payload.output.sentence.emo_tag and payload.output.sentence.emo_confidence. The value is one of three polarities: positive (such as happy or satisfied), negative (such as angry or subdued), and neutral (no clear emotion). The confidence ranges from 0.0 to 1.0. Emotion recognition is returned only when all of the following conditions are met:
  • The model is paraformer-realtime-8k-v2.
  • Semantic segmentation is off: semantic_punctuation_enabled = false (false is the default, so no special setting is needed).
  • The result is returned only in the sentence-end event, where sentence_end = true.
To stop returning the emotion fields, set semantic_punctuation_enabled to true. This enables semantic segmentation and no longer returns the emo_tag and emo_confidence fields. The field names above follow the WebSocket JSON paths. Different SDKs expose these fields with their own naming conventions (dictionary keys, object properties, getter methods, and so on). For the complete field mapping, see the API reference for each SDK. For the full field definitions, value constraints, and examples, see API reference.

Sensitive word filtering

Sensitive word filtering replaces or removes sensitive words in the recognition result. Use it for call-center quality inspection, content compliance, subtitle review, and similar scenarios. Supported models: Qwen-Audio-3.0-ASR-Flash-Streaming and Fun-ASR-Realtime only. Limit: You can set up to 32 sensitive words. Default behavior: When the special_word_filter parameter is not passed, no sensitive words are filtered. How to configure: special_word_filter is a JSON object with three subfields:
  • filter_with_signed.word_list: A string array that lists the sensitive words to replace with an equal-length string of * characters. For example, with ["test"], "Help me test it" becomes "Help me **** it".
  • filter_with_empty.word_list: A string array that lists the sensitive words to remove entirely from the result. For example, with ["start"], "Is the game about to start" becomes "Is the game about to".
  • system_reserved_filter: A boolean that defaults to false. It determines whether sensitive word filtering is enabled.
Configuration example:
{
  "special_word_filter": {
    "filter_with_signed": {
      "word_list": ["test"]
    },
    "filter_with_empty": {
      "word_list": ["start", "occur"]
    },
    "system_reserved_filter": true
  }
}
Different SDKs expose these parameters with their own naming conventions (dictionary keys, object properties, methods, and so on). For the complete field mapping, see the API reference.

Call the raw WebSocket protocol

The following examples show how to connect directly to the server over the raw WebSocket protocol, for scenarios that do not use the DashScope SDK. Each example is a minimal, runnable implementation. For the WebSocket protocol, see the API reference of each model.
  • Qwen-Audio-3.0-ASR-Flash-Streaming/ Fun-ASR-Realtime
  • Qwen3-ASR-Flash-Realtime
  • Paraformer
  • Python
  • Java
  • Node.js
  • C#
  • PHP
  • Go
Before you run the example, install the dependencies with the following commands:
pip uninstall websocket-client
pip uninstall websocket
pip install websocket-client
Do not name the example file websocket.py. This name conflicts with the websocket library and causes the following error: AttributeError: module 'websocket' has no attribute 'WebSocketApp'. Did you mean: 'WebSocket'?.
# pip install websocket-client
import os
import json
import time
import uuid
import threading
import websocket

# The API Key differs between the Singapore and Beijing regions. Get your API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: api_key = "sk-xxx"
api_key = os.environ.get('DASHSCOPE_API_KEY')
# The following is the configuration for the Singapore region. When calling, replace "{WorkspaceId}" with your actual workspace ID. Configurations differ by region.
url = 'wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference'  # WebSocket server address
audio_file = '{YOUR_AUDIO_FILE}'  # Replace with the path to your audio file

# Generate a 32-character random ID
TASK_ID = uuid.uuid4().hex[:32]

task_started = False  # Flag indicating whether the task has started

# Send the run-task instruction
def send_run_task(ws):
    run_task_message = {
        'header': {
            'action': 'run-task',
            'task_id': TASK_ID,
            'streaming': 'duplex'
        },
        'payload': {
            'task_group': 'audio',
            'task': 'asr',
            'function': 'recognition',
            'model': 'qwen-audio-3.0-asr-flash-streaming',
            'parameters': {
                'sample_rate': 16000,
                'format': 'wav'
            },
            'input': {}
        }
    }
    ws.send(json.dumps(run_task_message))

# Send the finish-task instruction
def send_finish_task(ws):
    finish_task_message = {
        'header': {
            'action': 'finish-task',
            'task_id': TASK_ID,
            'streaming': 'duplex'
        },
        'payload': {
            'input': {}
        }
    }
    ws.send(json.dumps(finish_task_message))

# Send the audio stream (send one binary chunk every 100ms)
def send_audio_stream(ws):
    chunk_size = 3200  # 100ms @ 16kHz 16bit mono
    try:
        with open(audio_file, 'rb') as f:
            while True:
                chunk = f.read(chunk_size)
                if not chunk:
                    break
                ws.send(chunk, opcode=websocket.ABNF.OPCODE_BINARY)
                time.sleep(0.1)
        print('Audio stream ended')
        send_finish_task(ws)
    except Exception as e:
        print('Error reading audio file:', e)
        ws.close()

# Send the run-task instruction when the connection opens
def on_open(ws):
    print('Connected to server')
    send_run_task(ws)

# Handle received messages
def on_message(ws, data):
    global task_started
    message = json.loads(data)
    event = message['header']['event']
    if event == 'task-started':
        print('Task started')
        task_started = True
        threading.Thread(target=send_audio_stream, args=(ws,), daemon=True).start()
    elif event == 'result-generated':
        print('Recognition result:', message['payload']['output']['sentence']['text'])
        if message['payload'].get('usage'):
            print('Task billing duration (seconds):', message['payload']['usage']['duration'])
    elif event == 'task-finished':
        print('Task finished')
        ws.close()
    elif event == 'task-failed':
        print('Task failed:', message['header'].get('error_message'))
        ws.close()
    else:
        print('Unknown event:', event)

# Close the connection if the task-started event is not received
def on_close(ws, close_status_code, close_msg):
    if not task_started:
        print('Task not started, closing connection')

# Error handling
def on_error(ws, error):
    print('WebSocket error:', error)

if __name__ == '__main__':
    ws = websocket.WebSocketApp(
        url,
        header={'Authorization': f'bearer {api_key}'},
        on_open=on_open,
        on_message=on_message,
        on_error=on_error,
        on_close=on_close
    )
    ws.run_forever()

Apply in production

Reuse connections (WebSocket)

The WebSocket connections for Qwen-Audio-3.0-ASR-Flash-Streaming/Fun-ASR-Realtime and Paraformer support reuse: after one recognition task finishes, you can start the next task without reestablishing the connection. Reuse flow: The client sends finish-task. After the server returns task-finished, the client can send run-task again to start a new task.
  1. Wait for the server to return the task-finished event before starting a new task.
  2. Different tasks over a reused connection must use different task_id values.
  3. When a task fails, the server returns an error event and closes the connection. That connection cannot be reused.
  4. If no new task starts within 60 seconds after a task ends, the connection closes automatically.
Qwen3-ASR-Flash-Realtime uses a session model and does not support connection reuse. Close the connection after each session ends. For the events of each model, see the corresponding API reference.

High-concurrency best practices

The DashScope SDK includes a built-in pooling mechanism that reuses WebSocket connections and recognition objects, which avoids the overhead of frequent creation and destruction.
Currently, only the Java SDK supports this feature.

Prerequisites

The Java SDK combines a built-in connection pool with a custom object pool to achieve optimal performance:
  • Connection pool: The OkHttp3 connection pool integrated in the SDK manages and reuses the underlying WebSocket connections, which reduces network handshake overhead. This feature is enabled by default.
  • Object pool: Built on commons-pool2, the object pool maintains a set of Recognition objects whose connections are already established. Borrowing an object from the pool eliminates the connection setup latency and significantly reduces first-packet latency.

Implementation steps

  1. Add dependencies Add dashscope-sdk-java and commons-pool2 to your dependency configuration file, based on your project's build tool. The following examples show the configuration for Maven and Gradle:
    • Maven
    • Gradle
    1. Open the pom.xml file of your Maven project.
    2. Add the following dependencies inside the <dependencies> tag.
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>dashscope-sdk-java</artifactId>
        <!-- Replace 'the-latest-version' with version 2.16.9 or later. You can look up version numbers at: https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
        <version>the-latest-version</version>
    </dependency>
    
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
        <!-- Replace 'the-latest-version' with the latest version. You can look up version numbers at: https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
        <version>the-latest-version</version>
    </dependency>
    
    1. Save the pom.xml file.
    2. Run a Maven command (such as mvn clean install or mvn compile) to update the project dependencies.
  2. Configure the connection pool Configure the key connection pool parameters through environment variables:

    Environment variable

    Description

    DASHSCOPE_CONNECTION_POOL_SIZE

    The connection pool size.

    Recommended value: at least twice the peak concurrency.

    Default value: 32.

    DASHSCOPE_MAXIMUM_ASYNC_REQUESTS

    The maximum number of asynchronous requests.

    Recommended value: the same as DASHSCOPE_CONNECTION_POOL_SIZE.

    Default value: 32.

    DASHSCOPE_MAXIMUM_ASYNC_REQUESTS_PER_HOST

    The maximum number of asynchronous requests per host.

    Recommended value: the same as DASHSCOPE_CONNECTION_POOL_SIZE.

    Default value: 32.

  3. Configure the object pool Configure the object pool size through an environment variable:

    Environment variable

    Description

    RECOGNITION_OBJECTPOOL_SIZE

    The object pool size.

    Recommended value: 1.5 to 2 times the peak concurrency.

    Default value: 500.

    • The object pool size (RECOGNITION_OBJECTPOOL_SIZE) must be less than or equal to the connection pool size (DASHSCOPE_CONNECTION_POOL_SIZE). Otherwise, when the object pool requests an object and the connection pool is full, the calling thread blocks.
    • The object pool size must not exceed your account's queries per second (QPS) limit.
    Create the object pool with the following code:
class RecognitionObjectPool {
    // ... For the full example, see the complete code.
    public static GenericObjectPool<Recognition> getInstance() {
        lock.lock();
        if (recognitionGenericObjectPool == null) {
            int objectPoolSize = getObjectivePoolSize();
            RecognitionObjectFactory recognitionObjectFactory =
                    new RecognitionObjectFactory();
            GenericObjectPoolConfig<Recognition> config =
                    new GenericObjectPoolConfig<>();
            config.setMaxTotal(objectPoolSize);
            config.setMaxIdle(objectPoolSize);
            config.setMinIdle(objectPoolSize);
            recognitionGenericObjectPool =
                    new GenericObjectPool<>(recognitionObjectFactory, config);
        }
        lock.unlock();
        return recognitionGenericObjectPool;
    }
}
  1. Borrow a Recognition object from the object pool When the number of unreturned objects exceeds the object pool limit, the system creates additional Recognition objects. These new objects must reestablish a WebSocket connection and cannot be reused.
recognizer = RecognitionObjectPool.getInstance().borrowObject();
  1. Perform speech recognition Call the call or streamCall method of the Recognition object to perform speech recognition.
  2. Return the Recognition object After the speech recognition task finishes, return the Recognition object so that it can be reused. Do not return objects with unfinished or failed tasks.
RecognitionObjectPool.getInstance().returnObject(recognizer);

Complete code

package org.alibaba.bailian.example.examples;

import com.alibaba.dashscope.audio.asr.recognition.Recognition;
import com.alibaba.dashscope.audio.asr.recognition.RecognitionParam;
import com.alibaba.dashscope.audio.asr.recognition.RecognitionResult;
import com.alibaba.dashscope.common.ResultCallback;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.ApiKey;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    public static void checkoutEnv(String envName, int defaultSize) {
        if (System.getenv(envName) != null) {
            System.out.println("[ENV CHECK]: " + envName + " "
                    + System.getenv(envName));
        } else {
            System.out.println("[ENV CHECK]: " + envName
                    + " Using Default which is " + defaultSize);
        }
    }

    public static void main(String[] args)
            throws NoApiKeyException, InterruptedException {
        // The following is the configuration for the China (Beijing) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. Configurations differ by region.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
        checkoutEnv("DASHSCOPE_CONNECTION_POOL_SIZE", 32);
        checkoutEnv("DASHSCOPE_MAXIMUM_ASYNC_REQUESTS", 32);
        checkoutEnv("DASHSCOPE_MAXIMUM_ASYNC_REQUESTS_PER_HOST", 32);
        checkoutEnv(RecognitionObjectPool.RECOGNITION_OBJECTPOOL_SIZE_ENV,
                RecognitionObjectPool.DEFAULT_OBJECT_POOL_SIZE);

        int threadNums = 3;
        String currentDir = System.getProperty("user.dir");
        Path[] filePaths = {
                Paths.get(currentDir, "{YOUR_AUDIO_FILE}"),
                Paths.get(currentDir, "{YOUR_AUDIO_FILE}"),
                Paths.get(currentDir, "{YOUR_AUDIO_FILE}"),
        };
        ExecutorService executorService = Executors.newFixedThreadPool(threadNums);
        for (int i = 0; i < threadNums; i++) {
            executorService.submit(new RealtimeRecognizeTask(filePaths));
        }
        executorService.shutdown();
        executorService.awaitTermination(10, TimeUnit.MINUTES);
        System.exit(0);
    }
}

class RecognitionObjectFactory extends BasePooledObjectFactory<Recognition> {
    public RecognitionObjectFactory() {
        super();
    }

    @Override
    public Recognition create() throws Exception {
        return new Recognition();
    }

    @Override
    public PooledObject<Recognition> wrap(Recognition obj) {
        return new DefaultPooledObject<>(obj);
    }
}

class RecognitionObjectPool {
    public static GenericObjectPool<Recognition> recognitionGenericObjectPool;
    public static String RECOGNITION_OBJECTPOOL_SIZE_ENV =
            "RECOGNITION_OBJECTPOOL_SIZE";
    public static int DEFAULT_OBJECT_POOL_SIZE = 500;
    private static Lock lock = new java.util.concurrent.locks.ReentrantLock();

    public static int getObjectivePoolSize() {
        try {
            Integer n = Integer.parseInt(
                    System.getenv(RECOGNITION_OBJECTPOOL_SIZE_ENV));
            return n;
        } catch (NumberFormatException e) {
            return DEFAULT_OBJECT_POOL_SIZE;
        }
    }

    public static GenericObjectPool<Recognition> getInstance() {
        lock.lock();
        if (recognitionGenericObjectPool == null) {
            int objectPoolSize = getObjectivePoolSize();
            System.out.println("RECOGNITION_OBJECTPOOL_SIZE: "
                    + objectPoolSize);
            RecognitionObjectFactory recognitionObjectFactory =
                    new RecognitionObjectFactory();
            GenericObjectPoolConfig<Recognition> config =
                    new GenericObjectPoolConfig<>();
            config.setMaxTotal(objectPoolSize);
            config.setMaxIdle(objectPoolSize);
            config.setMinIdle(objectPoolSize);
            recognitionGenericObjectPool =
                    new GenericObjectPool<>(recognitionObjectFactory, config);
        }
        lock.unlock();
        return recognitionGenericObjectPool;
    }
}

class RealtimeRecognizeTask implements Runnable {
    private static final Object lock = new Object();
    private Path[] filePaths;

    public RealtimeRecognizeTask(Path[] filePaths) {
        this.filePaths = filePaths;
    }

    private static String getDashScopeApiKey() throws NoApiKeyException {
        String dashScopeApiKey = null;
        try {
            ApiKey apiKey = new ApiKey();
            dashScopeApiKey = ApiKey.getApiKey(null);
        } catch (NoApiKeyException e) {
            System.out.println("No API key found in environment.");
        }
        if (dashScopeApiKey == null) {
            dashScopeApiKey = "your-dashscope-apikey";
        }
        return dashScopeApiKey;
    }

    public void runCallback() {
        for (Path filePath : filePaths) {
            RecognitionParam param = null;
            try {
                param = RecognitionParam.builder()
                        .model("paraformer-realtime-v2")
                        .format("pcm")
                        .sampleRate(16000)
                        .apiKey(getDashScopeApiKey())
                        .build();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            Recognition recognizer = null;
            final boolean[] hasError = {false};
            try {
                recognizer = RecognitionObjectPool.getInstance().borrowObject();
                String threadName = Thread.currentThread().getName();

                ResultCallback<RecognitionResult> callback =
                        new ResultCallback<RecognitionResult>() {
                            @Override
                            public void onEvent(RecognitionResult message) {
                                synchronized (lock) {
                                    if (message.isSentenceEnd()) {
                                        System.out.println("[process " + threadName
                                                + "] Fix:" + message.getSentence().getText());
                                    } else {
                                        System.out.println("[process " + threadName
                                                + "] Result: " + message.getSentence().getText());
                                    }
                                }
                            }

                            @Override
                            public void onComplete() {
                                System.out.println("[" + threadName
                                        + "] Recognition complete");
                            }

                            @Override
                            public void onError(Exception e) {
                                System.out.println("[" + threadName
                                        + "] RecognitionCallback error: " + e.getMessage());
                                hasError[0] = true;
                            }
                        };
                System.out.println("[" + threadName
                        + "] Input file_path is: " + filePath);
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(filePath.toFile());
                } catch (Exception e) {
                    System.out.println("Error when loading file: " + filePath);
                    e.printStackTrace();
                }
                recognizer.call(param, callback);

                // chunk size set to 100 ms for 16KHz sample rate
                byte[] buffer = new byte[3200];
                int bytesRead;
                while ((bytesRead = fis.read(buffer)) != -1) {
                    ByteBuffer byteBuffer;
                    if (bytesRead < buffer.length) {
                        byteBuffer = ByteBuffer.wrap(buffer, 0, bytesRead);
                    } else {
                        byteBuffer = ByteBuffer.wrap(buffer);
                    }
                    recognizer.sendAudioFrame(byteBuffer);
                    Thread.sleep(100);
                    buffer = new byte[3200];
                }
                System.out.println("[" + threadName + "] send audio done");
                recognizer.stop();
                System.out.println("[" + threadName + "] asr task finished");
            } catch (Exception e) {
                e.printStackTrace();
                hasError[0] = true;
            }
            if (recognizer != null) {
                try {
                    if (hasError[0] == true) {
                        recognizer.getDuplexApi().close(1000, "bye");
                        RecognitionObjectPool.getInstance()
                                .invalidateObject(recognizer);
                    } else {
                        RecognitionObjectPool.getInstance()
                                .returnObject(recognizer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void run() {
        runCallback();
    }
}

Recommended configuration

The following configurations are based on test results from running only the Paraformer real-time speech recognition service on Alibaba Cloud servers of the specified specifications. Single-machine concurrency is the number of Paraformer real-time speech recognition tasks running at the same time (that is, the number of worker threads).

Machine specification (Alibaba Cloud)

Max single-machine concurrency

Object pool size

Connection pool size

4 vCPUs, 8 GiB

100

500

2000

8 vCPUs, 16 GiB

200

500

2000

16 vCPUs, 32 GiB

400

500

2000

Resource management and error handling

  • Task succeeds: Call GenericObjectPool.returnObject() to return the Recognition object to the pool for reuse.
    Do not return Recognition objects with unfinished or failed tasks.
  • Task fails: When an exception thrown by the SDK or your business logic interrupts a task, perform the following two actions:
    1. Actively close the underlying WebSocket connection.
    2. Invalidate the object in the object pool to prevent it from being reused.
// Close the connection.
recognizer.getDuplexApi().close(1000, "bye");
// Invalidate the failed recognizer in the object pool.
RecognitionObjectPool.getInstance().invalidateObject(recognizer);
  • When the service returns a TaskFailed error, no extra handling is required.

Warm-up and latency measurement

When you evaluate performance such as concurrent call latency for the DashScope Java SDK, we recommend that you run a sufficient warm-up before the formal test.
Connection reuse mechanism
The DashScope Java SDK manages and reuses WebSocket connections through a global singleton connection pool. This mechanism works as follows:
  • On-demand creation: The SDK does not pre-create WebSocket connections at service startup. Instead, it establishes connections on demand at the first call.
  • Time-limited reuse: After a request completes, the connection stays in the pool for up to 60 seconds for reuse.
    • If a new request arrives within 60 seconds, the SDK reuses the existing connection and avoids the overhead of a repeated handshake.
    • If a connection stays idle for more than 60 seconds, the SDK closes it automatically to release resources.
Why warm-up matters
In the following scenarios, the connection pool might not have an active connection to reuse, so a request has to create a new connection:
  • The application has just started and has not made any calls yet.
  • The service has been idle for more than 60 seconds, so pooled connections have closed due to timeout.
In these scenarios, the first or early requests trigger the full WebSocket connection process (including the TCP handshake, TLS negotiation, and protocol upgrade). Their end-to-end latency is significantly higher than that of later requests that reuse connections.
Recommended approach
Before you run a formal load test or measure latency, follow these warm-up steps:
  1. Simulate the concurrency level of the formal test by sending a number of calls in advance (for example, for 1 to 2 minutes) to fully populate the connection pool.
  2. After you confirm that the connection pool has established and maintained enough active connections, start collecting the formal performance data.

Improve recognition accuracy

  • Choose a model that matches the sample rate: For 8 kHz telephone audio, use an 8 kHz model directly. This avoids the information loss caused by upsampling to 16 kHz.
  • Improve the input audio quality: Use a high-quality microphone and record in an environment with a high signal-to-noise ratio and no echo. At the application layer, you can integrate algorithms such as noise reduction (for example, RNNoise) and acoustic echo cancellation (AEC) for preprocessing.

Set up a fault-tolerance strategy

  • Client-side reconnection: The client should implement automatic reconnection to handle network jitter. The following is a reference implementation for the Python SDK:
    1. Catch exceptions: Implement the on_error method in the Callback class. The dashscope SDK calls this method when it encounters a network error or another issue.
    2. Signal the state: When on_error is triggered, set a reconnection signal. In Python, you can use threading.Event, a thread-safe signal flag.
    3. Reconnection loop: Wrap the main logic in a for loop (for example, retry 3 times). When the reconnection signal is detected, the current recognition round is interrupted, resources are cleaned up, and after a few seconds the loop runs again to create a brand-new connection.
  • Set a heartbeat to keep the connection alive: To maintain a long-lived connection with the server, set the heartbeat parameter to true. The connection to the server then stays open even when the audio contains no sound for a long time.
  • Model rate limits: When you call the model API, note the model's Rate limiting rules.

Supported models and regions

  • Singapore
  • China (Beijing)
To call the following models, use an API Key for the Singapore region:
  • Qwen-Audio-3.0-ASR-Flash-Streaming: qwen-audio-3.0-asr-flash-streaming
  • Fun-ASR-Realtime: fun-asr-realtime (stable version, currently equivalent to fun-asr-realtime-2025-11-07), fun-asr-realtime-2025-11-07 (snapshot version)
  • Qwen3-ASR-Flash-Realtime: qwen3-asr-flash-realtime (stable version, currently equivalent to qwen3-asr-flash-realtime-2025-10-27), qwen3-asr-flash-realtime-2026-02-10 (latest snapshot version), qwen3-asr-flash-realtime-2025-10-27 (snapshot version)

API reference

FAQ

Which audio formats does real-time speech recognition support?

The Qwen-Audio-3.0-ASR-Flash-Streaming, Fun-ASR-Realtime, and Paraformer models support the pcm, wav, mp3, opus, speex, aac, and amr formats. For the Qwen3-ASR-Flash-Realtime model, we recommend the pcm or opus format. Other formats (such as wav, aac, and amr) are accepted by the session.update validation layer, but the server-side decoding might fail. Confirm that the audio stream uses a recommended format before you send it.

What's the difference between the SDK and the WebSocket API, and how do I choose?

The DashScope SDK encapsulates details such as WebSocket connection management, authentication, and reconnection, which makes it a good fit for quick integration. Connecting directly to the WebSocket API provides finer-grained control and suits programming languages that the SDK does not cover or scenarios that require custom connection management. We recommend that you use the SDK first.

How do I improve recognition accuracy for proper nouns?

Use hotwords or context enhancement. For detailed configuration methods and usage notes, see Improve recognition accuracy.

What should I do when the connection drops frequently?

Implement client-side reconnection and enable the heartbeat parameter (heartbeat=true) to prevent the connection from dropping when there is no audio for a long time. For detailed fault-tolerance strategies, see Apply in production.
Token Plan
Model Playground
Statistics and Monitoring
Support