This topic describes the parameters and interfaces of the Python SDK for the Fun-ASR-Realtime real-time speech recognition model.
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 core resource (client.audio.asr) provides interfaces for both non-streaming and bidirectional streaming calls. Choose the call method that fits your needs:
- Non-streaming call (
recognize_file): Recognizes a local file. The SDK automatically sends the audio in chunks and drives the task to completion. Suitable for processing pre-recorded audio. - Bidirectional streaming call (
recognizesession): Recognizes an audio stream directly and outputs results in real time. The audio stream can come from an external device, such as a microphone, or be read from a local file. Suitable for scenarios that require immediate feedback.
- Non-streaming call
- Bidirectional streaming call
Submit a single real-time speech recognition task and get the recognition result synchronously by passing in a local file.Call the
recognize_file method of the core resource (client.audio.asr) to bind request parameters, pass in the local file path, and iterate server events to obtain the recognition result.Request parameters
Set request parameters through the recognize/recognize_file methods of the core resource (client.audio.asr): model, format, sample_rate, and vocabulary_id are named parameters, and the remaining parameters (such as max_sentence_silence and language_hints) are passed in through the parameters dictionary.
| Parameter | Type | Required | Description |
|---|---|---|---|
model | str | Yes | The model name. |
sample_rate | int | Yes | The sample rate, in Hz. Valid values: 8 kHz models support only 8000 Hz; other models support any sample rate. |
format | str | Yes | The audio format. Valid values:
|
vocabulary_id | str | 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. |
max_sentence_silence | int | 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: 1300. Valid values: [200, 6000]. |
multi_threshold_mode_enabled | bool | No | Whether to enable multi-threshold mode. When enabled, it prevents VAD segmentation from producing segments that are too long. Default: False. |
punctuation_prediction_enabled | bool | No | Whether to automatically add punctuation to recognition results:
|
heartbeat | bool | No | Whether to enable heartbeat packets. Default: False.
|
language_hints | list[str] | 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 1 value. If you set more, only the first value 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]. Value descriptions:
|
special_word_filter | str | 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. |
Pass the following parameters through the input keyword argument of the recognize/recognize_file methods. |
| Parameter | Type | Required | Description |
|---|---|---|---|
input | dict | No | The input object used to pass in the conversation context. Context enhancement improves recognition accuracy for domain-specific terms. For usage, see Quick start. Tip: The context parameter is supported only by the fun-asr-realtime models. The dict must include a context key whose value is a list of messages (list[dict]). Each message contains the following fields:
input_text and text types are each limited to 5 messages. When the limit is exceeded, only the 5 most recent messages are retained. The total text length per context turn cannot exceed 400 characters, and any excess is truncated from the end. Tip: When you pass context, the messages in context must follow a specific order: context messages must be arranged by conversation turn, and within each turn, the user message (input_text type) must precede its corresponding assistant message (text type). Note: This field requires SDK version 2.0.1 or later. See Example 1 below |
Key interfaces
Core resource (client.audio.asr)
Real-time speech recognition is mounted on the client.audio.asr resource: recognize creates a bidirectional streaming recognition session (Recognition), and recognize_file recognizes a local file in one call.
| Member method | Method signature | Description |
|---|---|---|
recognize | See Example 1 below | Creates a bidirectional streaming recognition session. Entering the with context automatically calls start to establish the connection and submit the task. Sending audio and consuming events must run concurrently (use it together with send_audio_frame, events()/results(), and stop). |
recognize_file | See Example 2 below | A non-streaming call based on a local file: it automatically sends the audio in chunks and drives the task to completion, yielding server events one by one. This method requires read permission on the file. |
start | See Example 3 below | Starts speech recognition: establishes the connection, submits the task, and waits for task-started. Automatically called when entering the with context. Audio can be sent only after a successful start. |
send_audio_frame | See Example 4 below | Pushes audio. Keep each pushed audio frame neither too large nor too small: about 100 ms per frame, between 1 KB and 16 KB. Recognition results are obtained by iterating events()/results(). |
stop | See Example 5 below | Stops speech recognition: it only notifies the server that the input is finished. The receiver thread must keep consuming events() until the task-finished event. |
events / results | See Example 6 below | Iterates server events: events() yields raw event dicts (the recognition text is in payload.output.sentence); results() yields only recognition result frames, returning typed Recognition result (RecognitionResult) objects (heartbeat frames are filtered out). |
close | See Example 7 below | Closes the recognition session. Called automatically when exiting the with context. |
request_id / first_package_delay / last_package_delay / last_response | See Example 8 below | Gets the request_id, first-packet delay (latency from sending the first audio packet to receiving the first recognition result), and last-packet delay (time from sending the stop command to receiving the last recognition result). Use them after the task completes; last_response is the raw message most recently read successfully, which you can use to retrieve a task-failed error. They remain readable after the session is closed. |
Event iteration (events()/results())
During a bidirectional streaming call, the server returns key process information and data to the client through events. In the receiver thread, iterate the session's events() (raw event dicts) or results() (typed recognition result frames) to handle the information and data returned by the server.
| Event/iteration method | Output | Return value | Description |
|---|---|---|---|
| See Example 1 below | task-started event | None | Read internally by start() and saved in last_response when it returns; not yielded again by events(). |
| See Example 2 below | event: server event dict | Iterator | Yields events whenever the server has a response. Recognition results are in payload.output.sentence and may be heartbeat or empty-text events, which the application can ignore as needed. Keep a single receiver thread consuming it; do not create multiple concurrent readers. |
| See Example 3 below | result: Recognition result (RecognitionResult) | Iterator | Yields only recognition result frames (heartbeat frames filtered out); the iteration ends after all recognition results are returned. |
| See Example 4 below | DashScopeError exception | None | Raised in the sending/receiving thread when an error occurs; catch it with try/except. |
| See Example 5 below | task-finished event | None | Yielded by events() after the server completes all recognition; the iteration then ends. You must still read this event after calling stop(). |
Response
Recognition result (RecognitionResult)
RecognitionResult represents a single recognition result frame yielded by the session's results() iteration (usable in both bidirectional streaming calls and non-streaming calls; events() yields raw event dicts, so use results() if you need this typed view).
| Parameter | Type | Description |
|---|---|---|
get_sentence | See Example 1 below | Gets the current recognized sentence and its timestamp information. This method returns Dict[str, Any] (single-sentence information). For details, see Sentence (Sentence). |
request_id | See Example 2 below | The request_id of the current event. |
is_sentence_end | See Example 3 below | Determines whether the current sentence has ended. This method checks whether the end_time field in the single-sentence information returned by get_sentence() is None: a non-None end_time indicates that the sentence has ended. |
Sentence information (Sentence)
The members of the Sentence class are as follows:
| Parameter | Type | Description |
|---|---|---|
begin_time | int | Sentence start time, in ms. |
end_time | int | Sentence end time, in ms. |
text | str | Recognized text. |
words | A list of Word-level timestamp information (Word) | Word-level timestamp information. |
Word-level timestamp information (Word)
The members of the Word class are as follows:
| Parameter | Type | Description |
|---|---|---|
begin_time | int | Word start time, in ms. |
end_time | int | Word end time, in ms. |
text | str | The word. |
punctuation | str | 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 alive during long periods of silence?
Set the heartbeat request parameter to true, and keep sending silent audio to the server.
Silent audio is content in an audio file or 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 command-line tools like FFmpeg.
Q: How do I convert audio to a supported format?
Use FFmpeg. For more usage, see the FFmpeg official website.
Q: How do I recognize a local file (recording)?
There are two ways to recognize a local file:
-
Pass the local file path directly: This way returns the complete result only after recognition finishes, so it isn't suitable for scenarios that need immediate feedback.
See Non-streaming call, and call the
recognize_filemethod to pass the file path and recognize the recording directly. -
Convert the local file to a binary stream for recognition: This way recognizes the file while streaming results, so it suits scenarios that need immediate feedback.
See Bidirectional streaming call, and send the binary stream to the server for recognition through the
send_audio_framemethod of the recognition session.
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 errors include:- The audio file has a .wav extension but is actually in MP3 format, while the
formatrequest parameter is set to mp3 (incorrect parameter setting). - The audio sample rate is 3600 Hz, but the
sampleRate/sample_raterequest parameter is set to 48000 (incorrect parameter setting).
- The audio file has a .wav extension but is actually in MP3 format, while the
- If none of the checks above reveal a problem, add custom hotwords to improve recognition of specific terms.