Prerequisites
Fun-ASR-Realtime
Prerequisites
- The service is activated and you have obtained and configured an API key. Configure the API key as an environment variable rather than hard-coding it in your code, to guard against security risks caused by code leaks.
- Install the latest DashScope SDK.
Endpoint — Fun-ASR-Realtime
Real-time recognition in the SDK uses a WebSocket interface. The endpoint is automatically determined by the workspace and region of Client (and includes the workspace ID). To switch to another region, set the region of the target region when constructing the Client.
- China (Beijing)
- Singapore
wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inferenceReplace {WorkspaceId} with your actual Workspace ID when calling.Quick start
Replace {WorkspaceId} with your workspace ID and {YOUR_AUDIO_FILE} with the path to a local 16 kHz WAV file. The example prints the transcription in the terminal.
Additional examples
Use the same examples for the models below. Replace the model ID using this table.
| Model | Model ID in the example |
|---|---|
| Qwen-Audio-ASR-Streaming | qwen-audio-3.1-asr-flash-streamingFor microphone input, use qwen-audio-3.0-asr-flash-streaming. |
| Qwen-Audio-ASR-Message | qwen-audio-3.1-asr-flash-messageSupports only a sample rate of 16000 Hz. |
| Fun-ASR-Realtime | fun-asr-realtime |
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 the request parameters and pass in the local file path, then iterate the server events to get the recognition results.Request parameters
Fun-ASR-Realtime
Shared reference
See the current Fun-ASR-Realtime Python SDK reference.
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 arguments. Pass max_sentence_silence and language_hints in 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 cutting sentences too long.Default value: False. |
punctuation_prediction_enabled | bool | No | Whether to automatically add punctuation to recognition results:
|
heartbeat | bool | No | Whether to enable heartbeat packets.Default value: 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.
Click to view the supported language codes
|
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. |
input when creating a session with recognize.
| Parameter | Type | Required | Description |
|---|---|---|---|
input | dict | No | The input object used to pass in the conversation context (context). The context assists recognition and improves recognition accuracy for domain-specific terms. For usage, see Improve recognition accuracy.The dict must include a context key whose value is a list of messages (list[dict]). Each message contains the following fields:
This field requires SDK version 2.0.1 or later. |
API reference
Fun-ASR-Realtime
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 | 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 together with send_audio_frame, events()/results(), and stop). | |
| recognize_file | 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 to recognize. | |
| start | 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 | Pushes audio. Each pushed audio stream should be neither too large nor too small: about 100 ms of audio per packet is recommended, with a size between 1 KB and 16 KB.Recognition results are obtained by iterating events()/results(). | |
| stop | Stops speech recognition: only notifies the server that the input has ended; the receiver thread must keep consuming events() until the task-finished event. | |
| events / results | 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 | Closes the recognition session. Automatically called when exiting the with context. | |
| request_id / first_package_delay / last_package_delay / last_response | Gets the request_id, the first-packet delay (latency from sending the first audio packet to receiving the first recognition result), and the last-packet delay (time from sending the stop command to the delivery of the last recognition result). Use them after the task completes; last_response is the most recent raw message successfully read, which you can use to retrieve task-failed errors. 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 a receiver thread, iterate the session's events() (raw event dicts) or results() (typed recognition result frames) to handle the information or data returned by the server.
| Event/iteration method | Output | Return value | Description |
|---|---|---|---|
task-started event | None | Read internally by start() and saved in last_response when the start returns; it is not yielded again by events(). | |
event: server event dict | Iterator | Yields events when the server responds. The recognition result is in payload.output.sentence, which may be a heartbeat or empty-text event that applications can ignore as needed. Consume it continuously from a single receiver thread; do not create multiple concurrent readers. | |
result: recognition result (RecognitionResult) | Iterator | Yields only recognition result frames (heartbeat frames are filtered out); the iteration ends after all recognition results are returned. | |
DashScopeError exception | None | Raised in the sending/receiving thread when an error occurs; catch it with try/except. | |
task-finished event | None | Yielded by events() when the server has completed all recognition, after which the iteration ends; you must still read this event after sending stop(). |
Response
Recognition result (RecognitionResult)
RecognitionResult represents a single recognition result frame yielded by iterating the session's results() (usable for both bidirectional streaming and non-streaming calls; events() yields raw event dicts—use results() if you need this typed view).
| Member method | Method signature | Description |
|---|---|---|
get_sentence | Gets the current recognized sentence and its timestamp information. This method returns Dict[str, Any] (single-sentence information).For details, see Sentence information (Sentence). | |
request_id | The request_id of the current event. | |
is_sentence_end | 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 timestamp information (Word) | Word timestamp information. |
Word 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. |