This topic describes the parameters and interfaces of the Java SDK for Qwen-Audio-ASR-Streaming real-time speech recognition.
Prerequisites
- The service is activated and Obtain an API key. To guard against security risks caused by code leaks, Configure API key as an environment variable, rather than hard-coding it in your code.
- Install the latest DashScope SDK.
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
- Bidirectional streaming call: callback-based
- Bidirectional streaming call: Flowable-based
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.High-concurrency calls
The DashScope Java SDK uses the connection pooling of OkHttp3 to reduce the overhead of repeatedly establishing connections. For details, see High-concurrency best practices.
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.
| Parameter | Type | Required | Description |
|---|---|---|---|
model | String | Yes | The model name. |
sampleRate | Integer | Yes | The sample rate in Hz. Any sample rate is supported. |
format | String | Yes | The audio format. Valid values:
|
keep_dialect | boolean | No | Supported by qwen-audio-3.1-asr-flash-streaming only. Defaults to false, which transcribes dialects into standard Chinese. Set to true to preserve dialect expressions. Set with .parameter("keep_dialect", value). See Client events for details. |
vad_model | String | No | Supported by qwen-audio-3.1-asr-flash-streaming only. Set to near_meeting_16k (near-field) or far_field_meeting_16k (far-field, default). Set with .parameter("vad_model", value). See Client events for details. |
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 instant and precompiled hotwords are configured together, the system merges both sets. If the merged set contains more than 2000 hotwords, the system randomly selects 2000 to use. For usage details, see Instant hotwords. Set vocabulary through the parameter method or the parameters method of the RecognitionParam instance: See Example 1 below See Example 2 below |
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. Default value: 800. Valid values: [200, 6000]. Set max_sentence_silence through the parameter method or the parameters method of the RecognitionParam instance: See Example 3 below See Example 4 below |
multi_threshold_mode_enabled | boolean | No | Whether to enable multi-threshold mode. When enabled, this prevents VAD segments from becoming too long. Default value: false. Set multi_threshold_mode_enabled through the parameter method or the parameters method of the RecognitionParam instance: See Example 5 below See Example 6 below |
punctuation_prediction_enabled | boolean | No | Sets whether to automatically add punctuation to the recognition results:
punctuation_prediction_enabled through the parameter method or the parameters method of the RecognitionParam instance: See Example 7 below See Example 8 below |
heartbeat | boolean | No | Whether to enable heartbeat packets. Default value: false.
heartbeat through the parameter method or the parameters method of the RecognitionParam instance: See Example 9 below See Example 10 below |
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. You can set up to 4 values. If you set more, only the first 4 take effect.
language_hints through the parameter method or the parameters method of the RecognitionParam instance: See Example 11 below See Example 12 below |
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]. Value descriptions:
speech_noise_threshold through the parameter method or the parameters method of the RecognitionParam instance: See Example 13 below See Example 14 below |
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. Set special_word_filter through the parameter method or the parameters method of the RecognitionParam instance: See Example 15 below See Example 16 below |
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. The Map must contain a context key whose value is a message array of type List<Map<String, Object>>. Each message contains the following fields:
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. Tip: 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). Note: To use this field, the SDK version must be 2.22.23 or later. Set input through the input method of the RecognitionParam instance: See Example 17 below |
apiKey | String | No | Your API key. |
Set through parameter
Set through parameters
Set through parameter
Set through parameters
Set through parameter
Set through parameters
Set through parameter
Set through parameters
Set through parameter
Set through parameters
Set through parameter
Set through parameters
Set through parameter
Set through parameters
Set through parameter
Set through parameters
Key interfaces
The 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 |
|---|---|---|---|
| See Example 1 below |
| None | Callback-based streaming real-time recognition. This method does not block the current thread. |
| See Example 2 below |
| 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. |
| See Example 3 below |
| Flowable<RecognitionResult> | Flowable-based streaming real-time recognition. |
| See Example 4 below |
| 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 The callback interface (ResultCallback). |
| See Example 5 below | None | None | Stops real-time recognition. This method blocks the current thread until the ResultCallback callback's onComplete or onError is called. |
| See Example 6 below | 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 best practices. |
| See Example 7 below | None | requestId | Gets the requestId of the current task. Available after a new task starts with call or streamingCall. Note: This method is available only in SDK version 2.18.0 and later. |
| See Example 8 below | 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. Note: This method is available only in SDK version 2.18.0 and later. |
| See Example 9 below | 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. Note: This method is available only in SDK version 2.18.0 and later. |
The 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.
| Parameter | Type | Required | Description |
|---|---|---|---|
| See Example 1 below | result: Real-time recognition result (RecognitionResult) | None | Called when the server sends a response. |
| See Example 2 below | None | None | Called after the task completes. |
| See Example 3 below | 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.
| Parameter | Type | Required | Description |
|---|---|---|---|
| See Example 1 below | None | requestId | Gets the requestId. |
| See Example 2 below | None | Whether a complete sentence has been formed, that is, whether a sentence boundary was detected. | Determines whether the given sentence has ended. |
| See Example 3 below | None | Sentence information (Sentence) | Gets the sentence information, including timestamps and text. |
Sentence information (Sentence)
| Parameter | Type | Required | Description |
|---|---|---|---|
| See Example 1 below | None | The sentence start time, in ms. | Returns the sentence start time. |
| See Example 2 below | None | The sentence end time, in ms. | Returns the sentence end time. |
| See Example 3 below | None | The recognized text. | Returns the recognized text. |
| See Example 4 below | None | A List of Word-level timestamp information (Word) objects. | Returns word-level timestamp information. |
Word-level timestamp information (Word)
| Parameter | Type | Required | Description |
|---|---|---|---|
| See Example 1 below | None | The word start time, in ms. | Returns the word start time. |
| See Example 2 below | None | The word end time, in ms. | Returns the word end time. |
| See Example 3 below | None | The word. | Returns the recognized word. |
| See Example 4 below | 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 listed in the speech SDK sample repository 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 isn't suitable for scenarios that need immediate feedback.
See Synchronous call, and pass the file path to the
callmethod of the 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 The Recognition class. - See Bidirectional streaming call: Flowable-based, and send the binary stream to the server for recognition through the
streamCallmethod of the 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.