Real-time ASR Java SDK for Qwen-Audio-3.0-ASR-Flash-Streaming/Fun-ASR-Realtime
User guide: For an introduction to the models and guidance on model selection, see Speech-to-text.
The Recognition class provides interfaces for both synchronous calls and bidirectional streaming calls. Choose the approach that fits your needs:
Submit a single real-time speech recognition task and get the recognition result synchronously by passing in a local file. The call blocks until the result is returned.
Instantiate the Recognition class, and call the
Submit a single real-time speech recognition task and stream the real-time recognition results by implementing a callback interface.
Submit a single real-time speech recognition task and stream the real-time recognition results by implementing a workflow (Flowable).
Flowable is an open-source framework for workflow and business process management, released under the Apache 2.0 license. For how to use Flowable, see Flowable API details.
The DashScope Java SDK uses the connection pooling of OkHttp3 to reduce the overhead of repeatedly establishing connections. For details, see Optimize Paraformer real-time speech recognition for high concurrency.
Use the chained methods of
Import
During bidirectional streaming calls, the server returns key process information and data to the client through callbacks. Implement the callback methods to handle the information or data returned by the server.
Implement the callback methods by extending the abstract class
If you encounter errors, see Error codes for troubleshooting.
If the issue persists, join the developer community to report your issue and provide the Request ID for further investigation.
Set the request parameter
Use the FFmpeg tool. For more usage, see the FFmpeg official website.
There are two ways to recognize a local file:
Quick start
The Recognition class provides interfaces for both synchronous calls and bidirectional streaming calls. Choose the approach that fits your needs:
- Synchronous call: Recognizes a local file and returns the complete result at once. Best for processing pre-recorded audio.
- Bidirectional streaming call: Recognizes an audio stream directly and returns results in real time. The audio stream can come from an external device, such as a microphone, or be read from a local file. Best for scenarios that require immediate feedback.
Synchronous call
Submit a single real-time speech recognition task and get the recognition result synchronously by passing in a local file. The call blocks until the result is returned.
Instantiate the Recognition class, and call the call method to bind request parameters and the file to recognize. The method performs recognition and returns the final result.
Click to view the full example
Click to view the full example
Bidirectional streaming call: callback-based
Submit a single real-time speech recognition task and stream the real-time recognition results by implementing a callback interface.
1
Start streaming recognition
Instantiate the Recognition class, and call the
call method to bind request parameters and the callback interface (ResultCallback) and start streaming speech recognition.2
Stream the audio
Call the
sendAudioFrame method of the Recognition class in a loop to send the binary audio stream to the server in segments. Read the audio from a local file or a device such as a microphone.While the audio data is being sent, the server returns recognition results to the client in real time through the onEvent method of the callback interface (ResultCallback).Send about 100 ms of audio per frame, keeping each payload between 1 KB and 16 KB.3
End the process
Call the
stop method of the Recognition class to end speech recognition.This method blocks the current thread until the onComplete or onError callback of the callback interface (ResultCallback) is triggered, at which point the thread is released.Click to view the full example
Click to view the full example
- Recognize speech from a microphone
- Recognize a local audio file
Bidirectional streaming call: Flowable-based
Submit a single real-time speech recognition task and stream the real-time recognition results by implementing a workflow (Flowable).
Flowable is an open-source framework for workflow and business process management, released under the Apache 2.0 license. For how to use Flowable, see Flowable API details.
Click to view the full example
Click to view the full example
Call the
streamCall method of the Recognition class directly to start recognition.The streamCall method returns a Flowable<RecognitionResult> instance. Use methods of the Flowable instance, such as blockingForEach or subscribe, to process the recognition results. Each result is wrapped in a RecognitionResult.The streamCall method takes two parameters:RecognitionParaminstance (Request parameters): use it to set the model, sample rate, audio format, and other parameters required for speech recognition.Flowable<ByteBuffer>instance: create an instance of typeFlowable<ByteBuffer>and implement the audio-stream parsing logic in it.
High-concurrency calls
The DashScope Java SDK uses the connection pooling of OkHttp3 to reduce the overhead of repeatedly establishing connections. For details, see Optimize Paraformer real-time speech recognition for high concurrency.
Request parameters
Use the chained methods of RecognitionParam to configure the model, sample rate, audio format, and other parameters. Pass the configured parameter object to the call/streamCall method of the Recognition class.
Click to view the example
Click to view the example
| Parameter | Type | Required | Description |
|---|---|---|---|
| model | String | Yes | The model name. The Qwen-Audio-3.0-ASR-Flash-Streaming and Fun-ASR-Realtime model series are supported. For details, see Supported models. |
| sampleRate | Integer | Yes | The sample rate, in Hz. Valid values: 8 kHz models support only 8000 Hz; other models support any sample rate. |
| format | String | Yes | The audio format. Valid values: pcm, wav, mp3, opus, speex, aac, amr. opus/speex: Must use Ogg encapsulation. wav: Must use PCM encoding. amr: Only the AMR-NB type is supported. |
| vocabularyId | String | No | The ID of a precompiled hot word list. Generate this ID in advance by calling the create hot word list API. Pass the ID during recognition to use the hot words in the list. Suitable for scenarios where the vocabulary is known and relatively stable, and where you need to reuse the same word list across requests. For usage details, see Precompiled hotwords. |
| vocabulary | Map<String, Integer> | No | Instant hot words. Passed as key-value pairs, where the key is the hot word text (string) and the value is the hot word weight (integer). No hot word list needs to be created in advance. The weight ranges from [1, 5] or is set to 50: a value in [1, 5] makes the model more likely to output the word as the value increases; a value of 50 designates a super hot word, which greatly improves recall, but the number of super hot words cannot exceed 50. Suitable for temporary, session-level hot word optimization. When configured together with precompiled hot words, only the instant hot words take effect. For usage details, see Instant hotwords. Only qwen-audio-3.0-asr-flash-streaming supports instant hot words. |
| semantic_punctuation_enabled | boolean | No | Whether to enable semantic segmentation. Default value: false. true: Enables semantic segmentation and disables VAD segmentation. false (default): Enables VAD segmentation and disables semantic segmentation. Semantic segmentation is more accurate and is better suited to meeting transcription scenarios. VAD (Voice Activity Detection) segmentation has lower latency and is better suited to interactive scenarios. |
| max_sentence_silence | Integer | No | The VAD silence threshold for segmentation, in ms. When the silence after a segment of speech exceeds this threshold, the system determines that the sentence has ended. When semantic_punctuation_enabled is set to true, this parameter is not used as the criterion for returning sentence_end, but setting it too low may affect recognition performance. Default value: 1300. Valid values: [200, 6000]. |
| multi_threshold_mode_enabled | boolean | No | Takes effect only when semantic_punctuation_enabled is false. |
| punctuation_prediction_enabled | boolean | No | Sets whether to automatically add punctuation to the recognition results: true (default): yes. This value cannot be changed. |
| heartbeat | boolean | No | Whether to enable heartbeat packets. Default value: false. true: Keeps the connection to the server alive even when silent audio is sent continuously. false (default): Even when silent audio is continuously sent, the connection times out and closes after a period of time. Silent audio refers to content in an audio file or data stream that contains no sound signal. You can generate silent audio in several ways, such as using audio editing software like Audacity or Adobe Audition, or using a command-line tool like FFmpeg. To use this field, the SDK version must be 2.19.1 or later. |
| language_hints | String[] | No | The language of the audio to recognize. There is no default value; if not set, the model detects the language automatically. For the Qwen-Audio-3.0-ASR-Flash-Streaming model series, you can set up to 4 values; if you set more than 4, only the first 4 take effect. For the Fun-ASR-Realtime model series, you can set only 1 value; if you set multiple values, only the first one takes effect. |
| speech_noise_threshold | float | No | The threshold for distinguishing speech from noise, used to adjust the sensitivity of Voice Activity Detection (VAD). Valid values: [-1.0, 1.0]. The closer the value is to -1: The noise threshold decreases, so noise is more likely to be recognized as speech, which may cause more noise to be transcribed. The closer the value is to +1: The noise threshold increases, so speech is more likely to be misjudged as noise, which may cause some speech to be filtered out. This is an advanced configuration parameter. Adjusting it can significantly affect recognition results. Recommendations: Thoroughly test and verify the results before adjusting. Adjust in small increments based on the actual audio environment (a step of 0.1 is recommended). |
| special_word_filter | String | No | Specifies the sensitive words to process during speech recognition, and supports setting different processing methods for different sensitive words. For details, see Sensitive word filtering. |
| input | Map<String, Object> | No | Input object that passes in the conversation context. The context helps recognition and improves the recognition accuracy of proper terms. For usage, see Quick start. Only the qwen-audio-3.0-asr-flash-streaming, fun-asr-realtime, and fun-asr-realtime-2025-11-07 models support the context parameter.context key whose value is a message array of type List<Map<String, Object>>. Each message contains the following fields: role (String, required): the message role. user indicates the recognition result of the user's speech from previous rounds or a domain-specific word list. assistant indicates the large language model's replies from previous rounds. content (List<Map>, required): the message content list. Each element contains type (String; set to input_text when role is user, and text when role is assistant) and text (String, the text content). Limits: context messages of the input_text and text types are limited to 5 each; the most recent 5 are kept when the limit is exceeded. The total text length per round of context cannot exceed 400 characters, and any excess is truncated from the end.When you pass in context, the messages in context must follow a specific order: context messages must be arranged by conversation round, and within each round the user message (input_text type) must precede the corresponding assistant message (text type).To use this field, the SDK version must be 2.22.23 or later. |
| apiKey | String | No | Your API key. |
Set
vocabulary through the parameter method or the parameters method of the RecognitionParam instance:- Set through parameter
- Set through parameters
Set
input through the input method of the RecognitionParam instance:Set
special_word_filter through the parameter method or the parameters method of the RecognitionParam instance:- Set through parameter
- Set through parameters
For parameters not on the
RecognitionParam builder directly (such as semantic_punctuation_enabled, heartbeat, max_sentence_silence, multi_threshold_mode_enabled, punctuation_prediction_enabled, speech_noise_threshold, and language_hints), use the parameter or parameters method:- Set through parameter
- Set through parameters
Key interfaces
Recognition class
Import Recognition with import com.alibaba.dashscope.audio.asr.recognition.Recognition;. Its key interfaces are as follows:
| Interface/Method | Parameter | Return value | Description |
|---|---|---|---|
public void call(RecognitionParam param, final ResultCallback<RecognitionResult> callback) | param: Request parameters callback: The callback interface (ResultCallback) | None | Callback-based streaming real-time recognition. This method does not block the current thread. |
public String call(RecognitionParam param, File file) | param: Request parameters file: The audio file to recognize. | The recognition result. | Non-streaming recognition of a local file. This method blocks the current thread until the entire audio file is read. The file must be readable. |
public Flowable<RecognitionResult> streamCall(RecognitionParam param, Flowable<ByteBuffer> audioFrame) | param: Request parameters audioFrame: A Flowable<ByteBuffer> instance. | Flowable<RecognitionResult> | Flowable-based streaming real-time recognition. |
public void sendAudioFrame(ByteBuffer audioFrame) | audioFrame: A binary audio stream of type ByteBuffer. | None | Sends audio. Keep each pushed audio chunk within a reasonable size. A recommended chunk holds about 100 ms of audio and is 1 KB to 16 KB in size. Recognition results are delivered through the onEvent method of the callback interface (ResultCallback). |
public void stop() | None | None | Stops real-time recognition. This method blocks the current thread until the ResultCallback callback's onComplete or onError is called. |
boolean getDuplexApi().close(int code, String reason) | code: The WebSocket close code. reason: The reason for closing. For guidance on setting these two parameters, see The WebSocket Protocol. | true | After a task ends, always close the WebSocket connection, whether or not an exception occurred, to avoid connection leaks. To reuse connections for better efficiency, see High-concurrency management. |
public String getLastRequestId() | None | requestId | Gets the requestId of the current task. Available after a new task starts with call or streamingCall. This method is available only in SDK version 2.18.0 and later. |
public long getFirstPackageDelay() | None | The first-packet latency. | Gets the first-packet latency, that is, the delay from sending the first audio packet to receiving the first recognition result. Use it after the task completes. This method is available only in SDK version 2.18.0 and later. |
public long getLastPackageDelay() | None | The last-packet latency. | Gets the last-packet latency, that is, the time from sending the stop command to receiving the final recognition result. Use it after the task completes. This method is available only in SDK version 2.18.0 and later. |
Callback interface (ResultCallback)
During bidirectional streaming calls, the server returns key process information and data to the client through callbacks. Implement the callback methods to handle the information or data returned by the server.
Implement the callback methods by extending the abstract class ResultCallback. When you extend this class, you can set the generic type to RecognitionResult. RecognitionResult wraps the data structure returned by the server.
Because Java supports connection reuse, there is no onClose or onOpen.
Example
Example
| Interface/Method | Parameter | Return value | Description |
|---|---|---|---|
public void onEvent(RecognitionResult result) | result: Real-time recognition result (RecognitionResult) | None | Called when the server sends a response. |
public void onComplete() | None | None | Called after the task completes. |
public void onError(Exception e) | e: The exception information. | None | Called when an exception occurs. |
Response
Real-time recognition result (RecognitionResult)
RecognitionResult represents the result of a single real-time recognition.
| Interface/Method | Parameter | Return value | Description |
|---|---|---|---|
public String getRequestId() | None | requestId | Gets the requestId. |
public boolean isSentenceEnd() | None | Whether a complete sentence has been formed, that is, whether a sentence boundary was detected. | Determines whether the given sentence has ended. |
public Sentence getSentence() | None | Sentence information (Sentence) | Gets the sentence information, including timestamps and text. |
Sentence information (Sentence)
| Interface/Method | Parameter | Return value | Description |
|---|---|---|---|
public Long getBeginTime() | None | The sentence start time, in ms. | Returns the sentence start time. |
public Long getEndTime() | None | The sentence end time, in ms. | Returns the sentence end time. |
public String getText() | None | The recognized text. | Returns the recognized text. |
public List<Word> getWords() | None | A List of Word-level timestamp information (Word) objects. | Returns word-level timestamp information. |
Word-level timestamp information (Word)
| Interface/Method | Parameter | Return value | Description |
|---|---|---|---|
public long getBeginTime() | None | The word start time, in ms. | Returns the word start time. |
public long getEndTime() | None | The word end time, in ms. | Returns the word end time. |
public String getText() | None | The word. | Returns the recognized word. |
public String getPunctuation() | None | The punctuation. | Returns the punctuation. |
Error codes
If you encounter errors, see Error codes for troubleshooting.
If the issue persists, join the developer community to report your issue and provide the Request ID for further investigation.
FAQ
Features
Q: How do I keep the connection to the server alive during long periods of silence?
Set the request parameter heartbeat to true, and keep sending silent audio to the server.
Silent audio is audio that contains no sound signal in the file or data stream. You can generate silent audio in several ways, for example, by using audio editing software such as Audacity or Adobe Audition, or a command-line tool such as FFmpeg.
Q: How do I convert audio to a supported format?
Use the FFmpeg tool. For more usage, see the FFmpeg official website.
Q: How do I recognize a local file (a recording)?
There are two ways to recognize a local file:
-
Pass in the local file path directly: this approach returns the complete recognition result only after recognition finishes, so it is not suitable for scenarios that need immediate feedback.
See Synchronous call, and pass the file path to the
callmethod of the Recognition class to recognize the recording directly. -
Convert the local file to a binary stream for recognition: this approach recognizes the file and streams results at the same time, which suits scenarios that need immediate feedback.
- See Bidirectional streaming call: callback-based, and send the binary stream to the server for recognition through the
sendAudioFramemethod of the Recognition class. - See Bidirectional streaming call: Flowable-based, and send the binary stream to the server for recognition through the
streamCallmethod of the Recognition class.
- See Bidirectional streaming call: callback-based, and send the binary stream to the server for recognition through the
Troubleshooting
Q: Why can't the speech be recognized (no recognition result)?
-
Check that the audio format (
format) and sample rate (sampleRate/sample_rate) in the request parameters are correct and meet the parameter constraints. Common mistakes include:- The audio file has a .wav extension but is actually in MP3 format, while the request parameter
formatis set to mp3 (incorrect parameter setting). - The audio sample rate is 3600 Hz, but the request parameter
sampleRate/sample_rateis set to 48000 (incorrect parameter setting).
- The audio file has a .wav extension but is actually in MP3 format, while the request parameter
-
Check that the language set in
language_hintsmatches the actual language of the audio. For example, the audio is actually in Chinese, butlanguage_hintsis set toen(English). - If none of the checks above reveal a problem, configure custom hotwords to improve recognition of specific terms.