Prerequisites
- You have activated the service and obtained and configured an API Key. Configure the API Key in environment variables instead of hard-coding it in your code, to prevent security risks caused by code leaks.
- Install the latest DashScope SDK.
API endpoint — Qwen-Audio-ASR-Streaming / Fun-ASR-Realtime
Realtime recognition in the SDK uses the WebSocket interface, and the endpoint is automatically determined by the Client's workspace and region (including the WorkspaceId). To switch to another region, set the region to the corresponding region when constructing the Client.
Singapore
wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference
When making calls, replace {WorkspaceId} with your actual Workspace ID.
China (Beijing)
wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference
When making calls, replace {WorkspaceId} with your actual Workspace ID.
ImportantAlibaba Cloud Model Studio has launched workspace-specific domains for the China (Beijing) and Singapore regions, which deliver superior performance and higher stability for inference requests. We recommend migrating to the new domains:
- China (Beijing) region: migrate from
dashscope.aliyuncs.comto{WorkspaceId}.cn-beijing.maas.aliyuncs.com - Singapore region: migrate from
dashscope-intl.aliyuncs.comto{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
API endpoint — Qwen-Audio-ASR-Message
Realtime recognition in the SDK uses the WebSocket interface, and the endpoint is automatically determined by the Client's workspace and region (including the WorkspaceId). To switch to another region, set the region to the corresponding region when constructing the Client.
Singapore
wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference
When making calls, replace {WorkspaceId} with your actual Workspace ID.
China (Beijing)
wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference
When making calls, replace {WorkspaceId} with your actual Workspace ID.
ImportantAlibaba Cloud Model Studio has launched workspace-specific domains for the China (Beijing) and Singapore regions, which deliver superior performance and higher stability for inference requests. We recommend migrating to the new domains:
- China (Beijing) region: migrate from
dashscope.aliyuncs.comto{WorkspaceId}.cn-beijing.maas.aliyuncs.com - Singapore region: migrate from
dashscope-intl.aliyuncs.comto{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
QuickStart
The following call examples are shared. Replace the model ID in the examples according to the table below.
| Model | Model ID in the examples |
|---|---|
| Qwen-Audio-ASR-Streaming | qwen-audio-3.1-asr-flash-streamingThe microphone example uses qwen-audio-3.0-asr-flash-streaming. |
| Qwen-Audio-ASR-Message | qwen-audio-3.1-asr-flash-messageOnly a sample rate of 16000 Hz is supported. |
| Fun-ASR-Realtime | fun-asr-realtime |
The core resource (client.audio.asr) provides interfaces such as non-streaming calls and bidirectional streaming calls. Choose the appropriate calling method based on your actual needs:
- Non-streaming call (
recognize_file): performs recognition on local files; the SDK automatically sends the audio in chunks and drives the task to completion. Suitable for processing recorded audio. - Bidirectional streaming call (
recognizesession): performs recognition directly on audio streams 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
Submit a single realtime speech transcription task and obtain the transcription result synchronously in a blocking manner by passing in a local file.
Call the recognize_file method of the core resource (client.audio.asr) to bind request parameters and pass in a local file path, and iterate server-side events to obtain recognition results.
import os
import dashscope
# The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
client = dashscope.Client(
api_key=os.environ.get('DASHSCOPE_API_KEY'),
# The following is the configuration for the Singapore (ap-southeast-1) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
# Recognize a local audio file: recognize_file automatically sends the audio in chunks and drives the task to completion
for event in client.audio.asr.recognize_file(
'{YOUR_AUDIO_FILE}',
model='qwen-audio-3.1-asr-flash-streaming',
format='wav',
sample_rate=16000):
payload = event.get('payload') or {}
sentence = (payload.get('output') or {}).get('sentence') or {}
if sentence.get('text') and not sentence.get('heartbeat'):
print('识别结果:', sentence['text'])
Bidirectional streaming call
Submit a single realtime speech transcription task, with realtime recognition results streamed out by iterating events.
-
Start streaming speech recognition
Call the
recognizemethod of the core resource (client.audio.asr) to create a recognition session and bind request parameters, then enter thewithcontext (which automatically calls thestartmethod to establish the connection and send the task) to start streaming speech recognition. -
Streaming
Call the session's
send_audio_framemethod in a loop to send the binary audio stream read from a local file or a device (such as a microphone) to the server in segments. Sending and receiving must proceed concurrently: the receiving thread iterates server-side events through the session'sevents()method and returns recognition results to the client in real time.We recommend that the audio sent each time be about 100 milliseconds in duration, with the data size kept between 1 KB and 16 KB.
-
Finish processing
Call the session's
stopmethod to end the speech recognition.This method only notifies the server that the input has ended; the receiving thread must continue consuming
events()until thetask-finishedevent to obtain the final recognition results and statistics. Errors at the ws layer are raised asDashScopeErrorexceptions, which you can catch with try/except where you send or receive.
import os
import signal # for keyboard events handling (press "Ctrl+C" to terminate recording)
import sys
import dashscope
import pyaudio
from concurrent.futures import ThreadPoolExecutor
mic = None
stream = None
# Set recording parameters
sample_rate = 16000 # 麦克风与请求使用相同的采样率。Qwen-Audio-ASR-Message 仅支持 16000 Hz。
channels = 1 # mono channel
dtype = 'int16' # data type
format_pcm = 'pcm' # the format of the audio data
block_size = 3200 # number of frames per buffer
# Real-time speech recognition event receiver
def receive_events(rec):
for event in rec.events():
payload = event.get('payload') or {}
sentence = (payload.get('output') or {}).get('sentence') or {}
if sentence.get('text') and not sentence.get('heartbeat'):
print('Recognition text: ', sentence['text'])
if sentence.get('sentence_end'):
print(
'Recognition sentence end, request_id:%s, usage:%s'
% (rec.request_id, rec.usage))
def signal_handler(sig, frame):
print('Ctrl+C pressed, stop recognition ...')
# Stop recognition
recognition.stop()
print('Recognition stopped.')
print(
'[Metric] requestId: {}, first package delay ms: {}, last package delay ms: {}'
.format(
recognition.request_id,
recognition.first_package_delay,
recognition.last_package_delay,
))
# Forcefully exit the program
sys.exit(0)
# main function
if __name__ == '__main__':
# The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
client = dashscope.Client(
api_key=os.environ.get('DASHSCOPE_API_KEY'),
# The following is the configuration for the Singapore (ap-southeast-1) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
# Call recognition service, you can customize the recognition parameters, like model, format,
# sample_rate
with client.audio.asr.recognize(
model='qwen-audio-3.0-asr-flash-streaming',
format=format_pcm,
# 'pcm'、'wav'、'opus'、'speex'、'aac'、'amr', you can check the supported formats in the document
sample_rate=sample_rate,
) as recognition:
# Open the microphone
mic = pyaudio.PyAudio()
stream = mic.open(format=pyaudio.paInt16,
channels=1,
rate=sample_rate,
input=True)
with ThreadPoolExecutor(max_workers=1) as pool:
receiver = pool.submit(receive_events, recognition)
try:
# Send audio from the microphone until "Ctrl+C" is pressed
while stream:
data = stream.read(3200, exception_on_overflow=False)
recognition.send_audio_frame(data)
recognition.stop()
receiver.result()
finally:
# close must run inside the pool context to unblock the receiver
recognition.close()
stream.stop_stream()
stream.close()
mic.terminate()
stream = None
mic = None
import os
import time
import dashscope
from concurrent.futures import ThreadPoolExecutor
# The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
client = dashscope.Client(
api_key=os.environ.get('DASHSCOPE_API_KEY'),
# The following is the configuration for the Singapore (ap-southeast-1) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
from datetime import datetime
def get_timestamp():
now = datetime.now()
formatted_timestamp = now.strftime("[%Y-%m-%d %H:%M:%S.%f]")
return formatted_timestamp
# Real-time speech recognition event receiver
def receive_events(rec):
for event in rec.events():
payload = event.get('payload') or {}
sentence = (payload.get('output') or {}).get('sentence') or {}
if sentence.get('text') and not sentence.get('heartbeat'):
print(get_timestamp() + ' Recognition text: ', sentence['text'])
if sentence.get('sentence_end'):
print(get_timestamp() +
'Recognition sentence end, request_id:%s, usage:%s'
% (rec.request_id, rec.usage))
with client.audio.asr.recognize(
model='qwen-audio-3.1-asr-flash-streaming',
format='wav',
sample_rate=16000,
) as recognition:
with ThreadPoolExecutor(max_workers=1) as pool:
receiver = pool.submit(receive_events, recognition)
try:
audio_data: bytes = None
f = open("{YOUR_AUDIO_FILE}", 'rb')
if os.path.getsize("{YOUR_AUDIO_FILE}"):
# Read all the file data into the buffer at once
file_buffer = f.read()
f.close()
print("Start Recognition")
# Send 3200 bytes from the buffer at a time
buffer_size = len(file_buffer)
offset = 0
chunk_size = 3200
while offset < buffer_size:
# Calculate the size of the data chunk to send this time
remaining_bytes = buffer_size - offset
current_chunk_size = min(chunk_size, remaining_bytes)
# Extract the current data chunk from the buffer
audio_data = file_buffer[offset:offset + current_chunk_size]
# Send the audio data frame
recognition.send_audio_frame(audio_data)
# Update the offset
offset += current_chunk_size
# Add a delay to simulate real-time transmission
time.sleep(0.1)
recognition.stop()
receiver.result()
else:
raise Exception(
'The supplied file was empty (zero bytes long)')
finally:
# close must run inside the pool context to unblock the receiver
recognition.close()
print(
'[Metric] requestId: {}, first package delay ms: {}, last package delay ms: {}'
.format(
recognition.request_id,
recognition.first_package_delay,
recognition.last_package_delay,
))
Request parameters
Qwen-Audio-ASR-Streaming
Shared notes
For details, see the new Qwen-Audio-ASR-Streaming Python SDK.
Request parameters are set through the recognize/recognize_file methods of the core resource (client.audio.asr): model, format, sample_rate, and vocabulary_id can be passed in directly. Pass language_hints in through the parameters dictionary.
| Parameter | Type | Required | Description |
|---|---|---|---|
model | str | Yes | Model name. |
sample_rate | int | Yes | Sampling rate (Hz). Any sampling rate is supported. |
format | str | Yes | Audio format. Valid values:
Importantopus/speex: must use Ogg encapsulation; wav: must use PCM encoding; amr: only the AMR-NB type is supported. |
keep_dialect | bool | No | Only supported by qwen-audio-3.1-asr-flash-streaming. Defaults to false, which transcribes dialects into Standard Mandarin; when set to true, dialect expressions are retained. Pass it in through the parameters dictionary. For the complete parameter description, seeclient events。 |
vad_model | str | No | Only supported by qwen-audio-3.1-asr-flash-streaming. You can select near_meeting_16k (near-field) or far_field_meeting_16k (far-field, default). Pass it in through the parameters dictionary. For the complete parameter description, seeclient events。 |
vocabulary_id | str | No | The ID of a precompiled hotword list. You must call the hotword list creation API in advance to generate it; pass this ID during recognition to use the hotwords in the list. This is suitable for scenarios where the vocabulary is known and relatively stable and the same vocabulary needs to be reused across requests. For usage instructions, see precompiled hotwords. |
vocabulary | dict | No | Instant hotwords. Passed in as key-value pairs, where the key is the hotword text ( This is suitable for temporary, session-level hotword optimization. When configured together with precompiled hotwords, the system merges the two types of hotwords; if the merged total exceeds 2,000, 2,000 are randomly selected for use. For usage instructions, see instant hotwords. Example: |
max_sentence_silence | int | No | VAD silence threshold for sentence segmentation (ms). When the silence after a segment of speech exceeds this threshold, the system determines that the sentence has ended. Default value: 800. Value range: [200, 6000]. |
multi_threshold_mode_enabled | bool | No | Whether to enable multi-threshold mode. When enabled, it prevents VAD sentence segmentation from cutting overly long segments. Default value: False. |
punctuation_prediction_enabled | bool | No | Set whether to automatically add punctuation to recognition results:
|
heartbeat | bool | No | Whether to enable heartbeat packets. Default value: False.
Silent audio refers to content with no sound signal in an audio file or data stream. Silent audio can be generated in multiple ways, for example using audio editing software such as Audacity or Adobe Audition, or command-line tools such as FFmpeg. When using this field, the SDK version must be 2.0.1 or later. |
language_hints | list[str] | No | The language of the audio to be recognized. There is no default value; the model automatically recognizes the language when it is not set. You can set up to 4 values; when more are set, only the first 4 take effect. Click to view 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). Value range: [-1.0, 1.0]. Value description:
This is an advanced configuration parameter; adjusting it may significantly affect recognition performance. Recommendations:
|
special_word_filter | str | No | Specifies the sensitive words to be handled during speech recognition, and supports setting different handling methods for different sensitive words. For details, seeSensitive word filtering。 |
When creating a recognition session with recognize, pass in the context via input.
| Parameter | Type | Required | Description |
|---|---|---|---|
input | dict | No | The input object, used to pass in the conversation context. The context assists recognition and improves recognition accuracy for proper nouns. For usage details, seeQuickStart。 The dict must contain a
ImportantContext messages ( ImportantWhen carrying context, the message order in NoteWhen using this field, the SDK version must be 2.0.1 or later. |
Qwen-Audio-ASR-Message
Shared notes
See the new version of the Qwen-Audio-ASR-Message Python SDK.
Request parameters are set via the core resource (client.audio.asr) recognize/recognize_file methods: model, format, sample_rate, vocabulary_id can be passed in directly. Pass language_hints via the parameters dictionary.
| Parameter | Type | Required | Description |
|---|---|---|---|
model | str | Yes | The model name, set to qwen-audio-3.1-asr-flash-message. |
sample_rate | int | Yes | Sampling rate (Hz). Only |
format | str | Yes | Audio format. Valid values:
Importantopus/speex: must use Ogg encapsulation; wav: must use PCM encoding; amr: only the AMR-NB type is supported. |
disfluency_removal_enabled | bool | No | Whether to filter filler words and polish the output results, with a default value of false. Enabled when set to true. Passed in as a keyword argument of the same name. |
intermediate_result_enabled | bool | No | Whether to return streaming intermediate results, with a default value of false. When set to true, streaming intermediate results are returned. Passed in via the parameters dictionary. |
keep_dialect | bool | No | Defaults to false, transcribing dialects into Mandarin; when set to true, dialect expressions are preserved. Passed in via the parameters dictionary. For complete parameter descriptions, seeclient events。Only effective for the final result ( |
vad_model | str | No | Optional: near_meeting_16k (near-field) or far_field_meeting_16k (far-field, default value). Passed in via the parameters dictionary. For complete parameter descriptions, seeclient events。 |
vocabulary_id | str | No | Precompiled hotword list ID. You must call the hotword list creation API in advance to generate it; pass this ID during recognition to use the hotwords in the list. This is suitable for scenarios where the vocabulary is known and relatively stable and the same vocabulary needs to be reused across requests. For usage instructions, see precompiled hotwords. |
vocabulary | dict | No | Instant hotwords. Passed in as key-value pairs, where the key is the hotword text ( This is suitable for temporary, session-level hotword optimization. When configured together with precompiled hotwords, the system merges the two types of hotwords; if the merged total exceeds 2,000, 2,000 are randomly selected for use. For usage instructions, see instant hotwords. Example: |
language_hints | list[str] | No | The language of the audio to be recognized. There is no default value; the model automatically recognizes the language when it is not set. You can set up to 4 values; when more are set, only the first 4 take effect. Click to view supported language codes
Passed in via the Only effective for the final result ( |
max_sentence_silence | int | No | VAD sentence-break silence threshold (ms). When the silence after a speech segment exceeds this threshold, the system determines that the sentence has ended. Default value: 800. Value range: [200, 6000]. |
heartbeat | bool | No | Whether to enable heartbeat packets. Default value: False.
Silent audio refers to content with no sound signal in an audio file or data stream. Silent audio can be generated in multiple ways, for example using audio editing software such as Audacity or Adobe Audition, or command-line tools such as FFmpeg. This field was introduced in SDK 1.23.1 and is already included in version 2.0.1 and later. |
speech_noise_threshold | float | No | The threshold for distinguishing speech from noise, used to adjust the sensitivity of voice activity detection (VAD). Value range: [-1.0, 1.0]. Value description:
This is an advanced configuration parameter; adjusting it may significantly affect recognition performance. Recommendations:
|
When creating a recognition session with recognize, pass in the context via input.
| Parameter | Type | Required | Description |
|---|---|---|---|
input | dict | No | The input object, used to pass in the conversation context. The context assists recognition and improves recognition accuracy for proper nouns. For usage details, seeQuickStart。 The dict must contain a
ImportantContext messages ( ImportantWhen carrying context, the message order in NoteThis field was introduced in SDK 1.25.23 and is already included in version 2.0.1 and later. |
Fun-ASR-Realtime
Shared notes
See the new Fun-ASR-Realtime Python SDK.
Request parameters are set via the core resource (client.audio.asr) recognize/recognize_file methods: model, format, sample_rate, vocabulary_id can be passed in directly. Pass max_sentence_silence and language_hints via the parameters dictionary.
| Parameter | Type | Required | Description |
|---|---|---|---|
model | str | Yes | Model name. |
sample_rate | int | Yes | Sampling rate (Hz). Value range: 8k models support only 8000 Hz; other models support any sampling rate. |
format | str | Yes | Audio format. Valid values:
Importantopus/speex: must use Ogg encapsulation; wav: must use PCM encoding; amr: only the AMR-NB type is supported. |
vocabulary_id | str | No | The ID of a precompiled hotword list. You must call the hotword list creation API in advance to generate it; pass this ID during recognition to use the hotwords in the list. This is suitable for scenarios where the vocabulary is known and relatively stable and the same vocabulary needs to be reused across requests. For usage instructions, see precompiled hotwords. |
max_sentence_silence | int | No | VAD silence threshold for sentence segmentation (ms). When the silence after a segment of speech exceeds this threshold, the system determines that the sentence has ended. Default value: 1300. Value range: [200, 6000]. |
multi_threshold_mode_enabled | bool | No | Whether to enable multi-threshold mode. When enabled, it prevents VAD sentence segmentation from cutting overly long segments. Default value: False. |
punctuation_prediction_enabled | bool | No | Set whether to automatically add punctuation to recognition results:
|
heartbeat | bool | No | Whether to enable heartbeat packets. Default value: False.
Silent audio refers to content with no sound signal in an audio file or data stream. Silent audio can be generated in multiple ways, for example using audio editing software such as Audacity or Adobe Audition, or command-line tools such as FFmpeg. When using this field, the SDK version must be 2.0.1 or later. |
language_hints | list[str] | No | The language of the audio to be recognized. There is no default value; the model automatically recognizes the language when it is not set. Only one value can be set; when multiple values are set, only the first one takes effect. Click to view 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). Value range: [-1.0, 1.0]. Value description:
This is an advanced configuration parameter; adjusting it may significantly affect recognition performance. Recommendations:
|
special_word_filter | str | No | Specifies the sensitive words to be handled during speech recognition, and supports setting different handling methods for different sensitive words. For details, seeSensitive word filtering。 |
When creating a recognition session with recognize, pass in the context via input.
| Parameter | Type | Required | Description |
|---|---|---|---|
input | dict | No | The input object, used to pass in the conversation context. The context assists recognition and improves recognition accuracy for proper nouns. For usage details, seeImproves recognition accuracy。 ImportantOnly the The dict must contain a
ImportantContext messages ( ImportantWhen carrying context, the message order in NoteWhen using this field, the SDK version must be 2.0.1 or later. |
API reference
Qwen-Audio-ASR-Streaming / Fun-ASR-Realtime
Recognition result (RecognitionResult)
RecognitionResult represents a single recognition result frame iterated from the session's results() output (usable in both bidirectional streaming calls and non-streaming calls; events() yields raw event dicts—use results() instead if you need this typed view).
| Member methods | Method signature | Description |
|---|---|---|
get_sentence | | Obtains the currently recognized sentence and its timestamp information. This method returns a Dict[str, Any] (single sentence information). For details, see Single sentence information (Sentence). |
request_id | | The request_id of the request corresponding to 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—when end_time is not None, the sentence has ended. |
Single sentence information (Sentence)
The Sentence class members 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 | Word timestamp information (Word)list collection | Word timestamp information. |
Word timestamp information (Word)
The Word class members are as follows:
| Parameter | Type | Description |
|---|---|---|
begin_time | int | Word start time, in ms. |
end_time | int | Word end time, in ms. |
text | str | Word. |
punctuation | str | Punctuation. |
Qwen-Audio-ASR-Streaming
Key interfaces
Core resources (client.audio.asr)
Real-time speech recognition capabilities are mounted on the client.audio.asr resource: recognize creates a bidirectional streaming recognition session (Recognition), and recognize_file performs one-shot recognition on local files.
| Member methods | Method signature | Description |
|---|---|---|
recognize | | Creates a bidirectional streaming recognition session; when entering the Sending audio and consuming events must proceed concurrently (use together with |
recognize_file | | Non-streaming call based on a local file: automatically sends audio in chunks and drives the task to completion, yielding server-side events one by one. This method requires the file to be recognized to have readable permission. |
start | | Starts speech recognition: establishes the connection, sends the task, and waits for task-started. Automatically called when entering the with context; audio can only be sent after a successful start. |
send_audio_frame | | Pushes audio. Each pushed audio stream should not be too large or too small; it is recommended that each audio packet be around 100ms in duration and between 1KB and 16KB in size. Recognition results are obtained via event iteration ( |
stop | | Stops speech recognition: only notifies the server that input has ended; the receiving thread must continue consuming events() until the task-finished event. |
events / results | | Iterates server-side events: |
close | | Closes the recognition session. Automatically called when exiting the |
request_id / first_package_delay / last_package_delay / last_response | | Obtains the request_id, first-packet latency (the delay from sending the first audio packet to receiving the first recognition result), and last-packet latency (the time from sending the |
Event iteration (events()/results())
In bidirectional streaming calls, the server returns key process information and data to the client as events. You need to iterate the session's events() (raw event dicts) or results() (typed recognition result frames) in a receiving thread to process the information or data returned by the server.
# Iterate raw events: recognition text is in payload.output.sentence
def receive_events(rec):
for event in rec.events():
payload = event.get('payload') or {}
sentence = (payload.get('output') or {}).get('sentence') or {}
if sentence.get('text') and not sentence.get('heartbeat'):
print('识别文本:', sentence['text'])
# Or iterate recognition result frames only (returns RecognitionResult, heartbeat frames filtered out)
def receive_results(rec):
for result in rec.results():
sentence = result.get_sentence()
if sentence and 'text' in sentence:
print('识别文本:', sentence['text'])
| Event/iteration method | Output | Return value | Description |
|---|---|---|---|
|
| None | Read internally by |
|
| Iterator | Yields events when the server has a response. Recognition results are located in |
|
| Iterator | Only yields recognition result frames (heartbeat frames already filtered); the iteration ends after all recognition results have been returned. |
|
| None | Raised in the sending/receiving thread when an exception occurs; can be caught with try/except. |
|
| None | Yielded by |
Response results
- Recognition result (
RecognitionResult) - Sentence information (
Sentence) - Word timestamp information (
Word)
Qwen-Audio-ASR-Message
Key interfaces
Core resources (client.audio.asr)
Real-time speech recognition capabilities are mounted on the client.audio.asr resource: recognize creates a bidirectional streaming recognition session (Recognition), and recognize_file performs one-shot recognition on local files.
| Member methods | Method signature | Description |
|---|---|---|
recognize | | Creates a bidirectional streaming recognition session; when entering the Sending audio and consuming events must proceed concurrently (use together with |
recognize_file | | Non-streaming call based on a local file: automatically sends audio in chunks and drives the task to completion, yielding server-side events one by one. This method requires the file to be recognized to have readable permission. |
start | | Start speech recognition: establishes the connection, sends the task, and waits for |
send_audio_frame | | Push audio. Each pushed audio chunk should not be too large or too small; an audio duration of about 100ms per chunk is recommended, with a size between 1KB and 16KB. Recognition results are obtained through event iteration ( |
stop | | Stops speech recognition: only notifies the server that input has ended; the receiving thread must continue consuming events() until the task-finished event. |
events / results | | Iterates over server-side events: |
close | | Closes the recognition session. Automatically called when exiting the |
request_id / first_package_delay / last_package_delay / last_response | | Obtains the request_id, first-packet latency (the delay from sending the first audio packet to receiving the first recognition result), and last-packet latency (the time from sending the |
Update conversation context
Call update_context to update the conversation context while a recognition task is running, to assist in recognizing subsequent audio. This method requires DashScope Python SDK 2.0.1 or later.
def update_context(self, context: dict)
- When to call:after entering the
withcontext (which automatically callsstart) to start streaming recognition and before callingstop. - Parameters:
contextis a dictionary; pass in thepayload.inputobject of thecontinue-taskevent, which contains thecontextfield. Do not wrap it with additionalpayloadorinputlayers. - Scope and parameter constraints:see continue-task.
The following example reuses an already started recognition instance.
payload_input = {
"context": [
{
"role": "user",
"content": [{"type": "input_text", "text": "你好啊"}]
},
{
"role": "assistant",
"content": [{"type": "text", "text": "你好啊,我是通义千问,有什么可以帮助你的?"}]
}
]
}
recognition.update_context(context=payload_input)
Event iteration (events()/results())
During bidirectional streaming calls, the server returns key process information and data to the client as events. You need to iterate the session's events() (raw event dicts) or results() (typed recognition result frames) in the receiving thread to process the information or data returned by the server.
# 迭代原始事件:识别文本位于 payload.output.sentence
def receive_events(rec):
for event in rec.events():
payload = event.get('payload') or {}
sentence = (payload.get('output') or {}).get('sentence') or {}
if sentence.get('text') and not sentence.get('heartbeat'):
print('识别文本:', sentence['text'])
# 或只迭代识别结果帧(返回 RecognitionResult,心跳帧已过滤)
def receive_results(rec):
for result in rec.results():
sentence = result.get_sentence()
if sentence and 'text' in sentence:
print('识别文本:', sentence['text'])
| Event/iteration method | Output | Return value | Description |
|---|---|---|---|
|
| None | Read internally by |
|
| Iterator | Yields events when the server has a response. Recognition results are located in |
|
| Iterator | Only yields recognition result frames (heartbeat frames already filtered); the iteration ends after all recognition results have been returned. |
|
| None | Raised in the sending/receiving thread when an exception occurs; can be caught with try/except. |
|
| None | Yielded by |
Response results
Recognition result (RecognitionResult)
RecognitionResult represents a recognition result frame yielded by iterating the session's results() (usable in both bidirectional streaming calls and non-streaming calls; events() yields raw event dicts, so use results() instead if you need this typed view).
| Member methods | Method signature | Description |
|---|---|---|
get_sentence | | Obtains the currently recognized sentence and its timestamp information. This method returns a Dict[str, Any] (sentence information). For details, see Sentence information (Sentence). |
request_id | | The request_id of the request corresponding to 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—when end_time is not None, the sentence has ended. |
Sentence information (Sentence)
The Sentence class members 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 | Word timestamp information (Word)list collection | Word timestamp information. |
Word timestamp information (Word)
The Word class members are as follows:
| Parameter | Type | Description |
|---|---|---|
begin_time | int | Word start time, in ms. |
end_time | int | Word end time, in ms. |
text | str | Word. |
punctuation | str | Punctuation. |
Fun-ASR-Realtime
Key interfaces
Core resources (client.audio.asr)
Real-time speech recognition capabilities are mounted on the client.audio.asr resource: recognize creates a bidirectional streaming recognition session (Recognition), and recognize_file performs one-shot recognition on local files.
| Member methods | Method signature | Description |
|---|---|---|
recognize | | Creates a bidirectional streaming recognition session. When entering the with context, start is automatically called to establish the connection and send the task.Sending audio and consuming events must proceed concurrently (use together with |
recognize_file | | Non-streaming call based on a local file: automatically sends the audio in chunks and drives the task to completion, yielding server-side events one by one. This method requires read permission on the file to be recognized. |
start | | Starts speech recognition: establishes the connection, sends the task, and waits for task-started. Automatically called when entering the with context; audio can only be sent after a successful start. |
send_audio_frame | | Pushes audio. Each pushed audio stream should not be too large or too small; it is recommended that each audio packet be around 100ms in duration and between 1KB and 16KB in size. Recognition results are obtained by iterating |
stop | | Stops speech recognition: only notifies the server that input has ended; the receiving thread must continue consuming events() until the task-finished event. |
events / results | | Iterates over server-side events: events() yields raw event dicts (recognition text is located 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. Called automatically when exiting the with context. |
request_id / first_package_delay / last_package_delay / last_response | | Obtains request_id, first-packet latency (the delay from sending the first audio chunk to receiving the first recognition result), and last-packet latency (the time from sending the stop command to the delivery of the last recognition result); use these after the task completes. last_response is the most recently successfully read raw message and can be used to retrieve task-failed errors. It remains readable after the session is closed. |
Event iteration (events()/results())
During bidirectional streaming calls, the server returns key process information and data to the client as events. You need to iterate the session's events() (raw event dicts) or results() (typed recognition result frames) in the receiving thread to process the information or data returned by the server.
# 迭代原始事件:识别文本位于 payload.output.sentence
def receive_events(rec):
for event in rec.events():
payload = event.get('payload') or {}
sentence = (payload.get('output') or {}).get('sentence') or {}
if sentence.get('text') and not sentence.get('heartbeat'):
print('识别文本:', sentence['text'])
# 或只迭代识别结果帧(返回 RecognitionResult,心跳帧已过滤)
def receive_results(rec):
for result in rec.results():
sentence = result.get_sentence()
if sentence and 'text' in sentence:
print('识别文本:', sentence['text'])
| Event/iteration method | Output | Return value | Description |
|---|---|---|---|
|
| None | Read internally by |
|
| Iterator | Yields events when the server has a response. Recognition results are located in |
|
| Iterator | Only yields recognition result frames (heartbeat frames already filtered); the iteration ends after all recognition results have been returned. |
|
| None | Raised in the sending/receiving thread when an exception occurs; can be caught with try/except. |
|
| None | Yielded by |
Response results
- Recognition result (
RecognitionResult) - Sentence information (
Sentence) - Word timestamp information (
Word)
Error codes
If you encounter errors, see Error codes for troubleshooting.
If the issue persists, join the developer group listed in the Speech SDK sample repository to report the issue, and provide the Request ID for further troubleshooting.