This topic describes the parameters and interface details of the Paraformer real-time speech recognition Java SDK.
User guide: For model introduction and selection recommendations, see Real-time speech recognition - Fun-ASR/Paraformer.
Recognition class provides non-streaming and bidirectional streaming call interfaces. Choose the appropriate call method based on your needs:
Submit a single real-time speech-to-text task and synchronously obtain the transcription result by passing in a local file.
Instantiate Recognition class, call the
Submit a single real-time speech-to-text task and stream real-time recognition results through the callback interface.
Submit a single real-time speech-to-text task and stream real-time recognition results through a Flowable workflow.
Flowable is an open-source framework for workflow and business process management, released under the Apache 2.0 license. For more information about Flowable, see Flowable API documentation.
The DashScope Java SDK uses OkHttp3 connection pooling to reduce the overhead of repeatedly establishing connections. For more information, see Optimize Paraformer real-time speech recognition for high concurrency.
Configure parameters such as the model, sample rate, and audio format through the chained methods of
During bidirectional streaming calls, the server returns key process information and data to the client through callbacks. You need to implement the callback methods to handle the information or data returned by the server.
Callback methods are implemented 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.
For more examples, see GitHub.
Set the request parameter
You can use the FFmpeg tool. For more usage, refer to the FFmpeg official website.
Yes. The speech recognition results include the start and end timestamps for each sentence, which can be used to determine the time range of each sentence.
There are two ways to recognize local files:
Prerequisites
When you need to provide temporary access to third-party applications or users, or when you want to strictly control high-risk operations such as accessing or deleting sensitive data, we recommend using temporary authentication tokens.Compared with long-term API Keys, temporary authentication tokens have a short validity period (60 seconds) and higher security, making them suitable for temporary call scenarios and effectively reducing the risk of API Key leakage.Usage: In your code, replace the API Key originally used for authentication with the obtained temporary authentication token.
Model list
| paraformer-realtime-v2 | paraformer-realtime-8k-v2 | |
|---|---|---|
| Use case | Live streaming, meetings, and similar scenarios | Recognition of 8 kHz audio in scenarios such as telephone customer service and voicemail |
| Sample rate | Any | 8kHz |
| Language | Chinese (including Mandarin and various dialects), English, Japanese, Korean, German, French, RussianSupported Chinese dialects: Shanghainese, Wu, Minnan, Northeastern, Gansu, Guizhou, Henan, Hubei, Hunan, Jiangxi, Ningxia, Shanxi, Shaanxi, Shandong, Sichuan, Tianjin, Yunnan, Cantonese | Chinese |
| Punctuation prediction | Supported by default, no configuration required | Supported by default, no configuration required |
| Inverse text normalization (ITN) | Supported by default, no configuration required | Supported by default, no configuration required |
| Custom hot words | See Custom hotwords | See Custom hotwords |
| Specify recognition language | Specify via the language_hints parameter | |
| Sentiment recognition |
(Click to view usage) Sentiment recognition follows these constraints:
getEmoTag and getEmoConfidence methods of Sentence information (Sentence) to obtain the sentiment and sentiment confidence of the current sentence respectively. |
Quick start
Recognition class provides non-streaming and bidirectional streaming call interfaces. Choose the appropriate call method based on your needs:
- Non-streaming call: Recognizes local files and returns the complete result at once. Suitable for processing pre-recorded audio.
- Bidirectional streaming call: Recognizes audio streams directly and outputs results in real time. The audio stream can come from external devices (such as a microphone) or be read from a local file. Suitable for scenarios that require immediate feedback.
Non-streaming call
Submit a single real-time speech-to-text task and synchronously obtain the transcription result by passing in a local file.
call method with Request parameters and the file to be recognized, perform recognition, and obtain the recognition result.
Click to view complete example
Click to view complete example
Bidirectional streaming: callback-based
Submit a single real-time speech-to-text task and stream real-time recognition results through the callback interface.
-
Start streaming speech recognition
Instantiate Recognition class, call the
callmethod with Request parameters and Callback interface (ResultCallback) to start streaming speech recognition. -
Stream audio data
Call the
sendAudioFramemethod of Recognition class in a loop to send binary audio stream segments read from a local file or device (such as a microphone) to the server. During the audio data transmission, the server returns recognition results to the client in real time through theonEventmethod of Callback interface (ResultCallback). It is recommended that each audio segment is approximately 100 milliseconds in duration, with a data size between 1 KB and 16 KB. -
Finish processing
Call the
stopmethod of Recognition class to end speech recognition. This method blocks the current thread until theonCompleteoronErrorcallback of Callback interface (ResultCallback) is triggered.
Click to view complete example
Click to view complete example
Bidirectional streaming: Flowable-based
Submit a single real-time speech-to-text task and stream real-time recognition results through a Flowable workflow.
Flowable is an open-source framework for workflow and business process management, released under the Apache 2.0 license. For more information about Flowable, see Flowable API documentation.
Click to view complete example
Click to view complete example
Directly call the
streamCall method of Recognition class to start recognition.The streamCall method returns a Flowable<RecognitionResult> instance. You can call methods such as Flowable instance's blockingForEach and subscribe to process recognition results. The recognition results are encapsulated in RecognitionResult.The streamCall method requires two parameters:RecognitionParaminstance (Request parameters): Use it to set parameters such as the model, sample rate, and audio format for speech recognition.Flowable<ByteBuffer>instance: You need to create aFlowable<ByteBuffer>type instance and implement the audio stream parsing method within it.
High-concurrency calls
The DashScope Java SDK uses OkHttp3 connection pooling to reduce the overhead of repeatedly establishing connections. For more information, see Optimize Paraformer real-time speech recognition for high concurrency.
Request parameters
Configure parameters such as the model, sample rate, and audio format through the chained methods of RecognitionParam. Pass the configured parameter object to the call/streamCall method of Recognition class.
Click to view example
Click to view example
| Parameter | Type | Default | Required | Description |
|---|---|---|---|---|
| model | String | Yes | The model for real-time speech recognition. For more information, see Model list. | |
| sampleRate | Integer | Yes | Set the sample rate (in Hz) of the audio to be recognized.Varies by model:
| |
| format | String | Yes | Set the audio format to be recognized.Supported audio formats: pcm, wav, mp3, opus, speex, aac, amr. | |
| vocabularyId | String | No | Set the hot word ID. If not set, hot words will not take effect. Use this field to set the hot word ID for v2 and later models.In the current speech recognition session, the hot word information corresponding to this hot word ID will be applied. For detailed usage, see Custom hotwords. | |
| disfluencyRemovalEnabled | boolean | false | No | Set whether to filter filler words:
|
| language_hints | String[] | ["zh", "en"] | No | Set the language codes for recognition. If you cannot determine the language in advance, you can leave this unset and the model will automatically detect the language.Currently supported language codes:
language_hints must be set through the RecognitionParam instance's parameter method or parameters method: |
| semantic_punctuation_enabled | boolean | false | No | Set whether to enable semantic segmentation. Disabled by default.
semantic_punctuation_enabled parameter, you can flexibly switch the speech recognition segmentation method to suit different scenarios.This parameter only takes effect when the model is v2 or later.semantic_punctuation_enabled must be set through the RecognitionParam instance's parameter method or parameters method: |
| max_sentence_silence | Integer | 800 | No | Set the silence duration threshold (in ms) for VAD (Voice Activity Detection) segmentation.When the silence duration after a speech segment exceeds this threshold, the system determines that the sentence has ended.The parameter range is 200 ms to 6000 ms, with a default value of 800 ms.This parameter only takes effect when the semantic_punctuation_enabled parameter is false (VAD segmentation) and the model is v2 or later.max_sentence_silence must be set through the RecognitionParam instance's parameter method or parameters method: |
| multi_threshold_mode_enabled | boolean | false | No | When this switch is enabled (true), it prevents VAD segmentation from cutting sentences that are too long. Disabled by default.This parameter only takes effect when the semantic_punctuation_enabled parameter is false (VAD segmentation) and the model is v2 or later.multi_threshold_mode_enabled must be set through the RecognitionParam instance's parameter method or parameters method: |
| punctuation_prediction_enabled | boolean | true | No | Set whether to automatically add punctuation in the recognition results:
punctuation_prediction_enabled must be set through the RecognitionParam instance's parameter method or parameters method: |
| heartbeat | boolean | false | No | When you need to maintain a long connection with the server, use this switch to control the behavior:
The SDK version must be 2.19.1 or later to use this field. heartbeat must be set through the RecognitionParam instance's parameter method or parameters method: |
| inverse_text_normalization_enabled | boolean | true | No | Set whether to enable ITN (Inverse Text Normalization).Enabled by default (true). When enabled, Chinese numerals are converted to Arabic numerals.This parameter only takes effect when the model is v2 or later.inverse_text_normalization_enabled must be set through the RecognitionParam instance's parameter method or parameters method: |
| apiKey | String | No | User API Key. |
Key interfaces
Recognition class
Recognition is imported via "import com.alibaba.dashscope.audio.asr.recognition.Recognition;". Its key interfaces are as follows:
| Interface/Method | Parameter | Return value | Description |
|---|---|---|---|
| None | Callback-based streaming real-time recognition. This method does not block the current thread. | |
| Recognition result | Non-streaming call based on a local file. This method blocks the current thread until all audio has been read. The file to be recognized must have read permissions. | |
| Flowable<RecognitionResult> | Flowable-based streaming real-time recognition. | |
| None | Send audio data. Each audio packet should not be too large or too small. It is recommended that each packet is approximately 100 ms in duration, with a size between 1 KB and 16 KB.Recognition results are obtained through the onEvent method of Callback interface (ResultCallback). | |
| None | None | Stop real-time recognition.This method blocks the current thread until the ResultCallback instance's onComplete or onError method is called. | |
| code: WebSocket close codereason: Close reasonThese two parameters can be configured according to The WebSocket Protocol documentation. | true | After the task ends, the WebSocket connection must be closed regardless of whether an exception occurred, to avoid connection leaks. For information on how to reuse connections to improve efficiency, see Optimize Paraformer real-time speech recognition for high concurrency. | |
| None | requestId | Get the requestId of the current task. Available after starting a new task with call or streamingCall.This method is available starting from SDK version 2.18.0. | |
| None | First package delay | Get the first package delay, which is the latency from sending the first audio packet to receiving the first recognition result. Use after the task is complete. This method is available starting from SDK version 2.18.0. | |
| None | Last package delay | Get the last package delay, which is the latency from sending the stop command to receiving the last recognition result. Use after the task is complete.This method is available starting from SDK version 2.18.0. |
Callback interface (ResultCallback)
During bidirectional streaming calls, the server returns key process information and data to the client through callbacks. You need to implement the callback methods to handle the information or data returned by the server.
Callback methods are implemented by extending the abstract class ResultCallback. When extending this abstract class, you can specify the generic type as RecognitionResult. RecognitionResult encapsulates the data structure returned by the server.
Since Java supports connection reuse, there are no onClose or onOpen callbacks.
Example
Example
| Interface/Method | Parameter | Return value | Description |
|---|---|---|---|
result: Real-time recognition result (RecognitionResult) | None | Called when the server has a response. | |
| None | None | Called when the task is complete. | |
e: Exception information | None | Called when an exception occurs. |
Response
Real-time recognition result (RecognitionResult)
RecognitionResult represents the result of a real-time recognition session.
| Interface/Method | Parameter | Return value | Description |
|---|---|---|---|
| None | requestId | Get the requestId. | |
| None | Whether it is a complete sentence, i.e., a sentence boundary has been reached | Determine whether the given sentence has ended. | |
| None | Sentence information (Sentence) | Get sentence information, including timestamps and text. |
Sentence information (Sentence)
| Interface/Method | Parameter | Return value | Description |
|---|---|---|---|
| None | Sentence start time in ms | Returns the sentence start time. | |
| None | Sentence end time in ms | Returns the sentence end time. | |
| None | Recognition text | Returns the recognized text. | |
| None | List of Word timestamp information (Word) | Returns word-level timestamp information. | |
| None | Sentiment of the current sentence | Returns the sentiment of the current sentence:
| |
| None | Sentiment confidence of the current sentence | Returns the sentiment confidence of the current sentence. Value range: [0.0, 1.0]. A higher value indicates higher confidence.Sentiment recognition follows these constraints:
|
Word timestamp information (Word)
| Interface/Method | Parameter | Return value | Description |
|---|---|---|---|
| None | Word start time in ms | Returns the word start time. | |
| None | Word end time in ms | Returns the word end time. | |
| None | Word | Returns the recognized word. | |
| None | 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.
More examples
For more examples, see GitHub.
FAQ
Feature questions
Q: How to maintain a long connection with the server during prolonged silence?
Set the request parameter heartbeat to true and continuously send silent audio to the server.
Silent audio refers to audio files or data streams that contain no sound signal. Silent audio can be generated through various methods, such as using audio editing software like Audacity or Adobe Audition, or through command-line tools like FFmpeg.
Q: How to convert audio to a supported format?
You can use the FFmpeg tool. For more usage, refer to the FFmpeg official website.
Q: Does it support viewing the time range for each sentence?
Yes. The speech recognition results include the start and end timestamps for each sentence, which can be used to determine the time range of each sentence.
Q: How to recognize a local file (recorded audio)?
There are two ways to recognize local files:
-
Pass the local file path directly: This method obtains the complete recognition result only after the entire recognition is finished, and is not suitable for scenarios requiring immediate feedback.
See Non-streaming call. Pass the file path to the
callmethod of Recognition class to directly recognize the recorded file. -
Convert the local file to a binary stream for recognition: This method recognizes the file while streaming the recognition results, suitable for scenarios requiring immediate feedback.
- See Bidirectional streaming: callback-based. Use the
sendAudioFramemethod of Recognition class to send the binary stream to the server for recognition. - See Bidirectional streaming: Flowable-based. Use the
streamCallmethod of Recognition class to send the binary stream to the server for recognition.
- See Bidirectional streaming: callback-based. Use the
Troubleshooting
Q: What causes the failure to recognize speech (no recognition results)?
-
Check whether the audio format (
format) and sample rate (sampleRate/sample_rate) in the request parameters are correctly set and comply with parameter constraints. The following are common error examples:- The audio file extension is .wav, but the actual format is MP3, and 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 extension is .wav, but the actual format is MP3, and the request parameter
-
When using the
paraformer-realtime-v2model, check whether the language set inlanguage_hintsmatches the actual language of the audio. For example: The audio is actually in Chinese, butlanguage_hintsis set toen(English). - If all the above checks pass, you can use custom hot words to improve recognition accuracy for specific words.