Python SDK
The parameters and interfaces of the Paraformer real-time speech recognition Python SDK.
ImportantAlibaba Cloud Model Studio has released a workspace-specific domain for the China (Beijing) region. The new dedicated domain delivers superior performance and higher stability for inference requests. We recommend migrating from dashscope.aliyuncs.com to {WorkspaceId}.cn-beijing.maas.aliyuncs.com.
Replace {WorkspaceId} with your actual Workspace ID. The existing domain remains fully functional.
User guide: For model introduction and selection recommendations, see Real-time speech recognition - Fun-ASR/Paraformer.
Prerequisites
You have activated the service and Obtain an API key. Please Configure API key as an environment variable instead of hardcoding it in your code to prevent security risks caused by code leakage.
NoteWhen 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 (Recommended) | paraformer-realtime-8k-v2 (Recommended) | |
|---|---|---|
| Scenarios | 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, Russian Supported 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 is required. | Supported by default. No configuration is required. |
| Inverse Text Normalization (ITN) | Supported by default. No configuration is required. | Supported by default. No configuration is required. |
| Custom vocabulary | ||
| Specify recognition language | Specify the language using the | Not supported |
| Emotion recognition | Not supported | Click to view usage Emotion recognition has the following constraints:
To obtain the emotion detection results, retrieve the emotion and the emotion confidence level of the current sentence from the |
Getting started
The core resource (client.audio.asr) provides non-streaming and bidirectional streaming call interfaces. You can select the appropriate method based on your requirements:
- Non-streaming call (
recognize_file): Recognizes a local file. The SDK automatically sends the audio in chunks and drives the task to completion. This is suitable for processing pre-recorded audio. - Bidirectional streaming call (
recognizesession): Recognizes an audio stream and outputs the results in real time. The audio stream can come from an external device, such as a microphone, or be read from a local file. This is suitable for scenarios that require immediate feedback.
Non-streaming call
This method submits a real-time speech-to-text task for a local file. The process is blocked until the complete transcription result is returned.
Call the recognize_file method of the core resource (client.audio.asr) with the request parameters and a local file path, and iterate the server events to obtain the RecognitionResult.
Click to view the complete example
import os
import dashscope
# China (Beijing): Replace {WorkspaceId} with your actual workspace ID. The configuration varies by region.
client = dashscope.Client(
# If you have not configured the API key in the environment variable, replace the following line with your API key: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="cn-beijing",
)
# 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='paraformer-realtime-v2',
format='wav',
sample_rate=16000,
# The "language_hints" parameter is supported only by the paraformer-realtime-v2 model.
parameters={'language_hints': ['zh', 'en']}):
payload = event.get('payload') or {}
sentence = (payload.get('output') or {}).get('sentence') or {}
if sentence.get('text') and not sentence.get('heartbeat'):
print('Recognition result: ', sentence['text'])
recognize_file yields server events one by one (Dict[str, Any]): the event type is located in event['header']['event'], and the recognized text is located in event['payload']['output']['sentence'] (sentence_end being true indicates that the sentence has ended; begin_time / end_time are timestamps, words contains per-word timestamps, and other fields are described in Sentence). Heartbeat and empty-text events are still yielded and can be ignored as needed.
In a bidirectional streaming session, in addition to events(), you can use results() to iterate only recognition result frames, which return typed RecognitionResult objects with heartbeat frames filtered out. For more information, see the get_sentence method.
Bidirectional streaming call
This method submits a real-time speech-to-text task and streams real-time recognition results by iterating events.
-
Start streaming speech recognition
Call the
recognizemethod of the core resource (client.audio.asr) to create a recognition session with the request parameters. Enter thewithcontext (which automatically calls thestartmethod to establish the connection and submit the task) to start streaming speech recognition. -
Streaming
Repeatedly call the session's
send_audio_framemethod 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 be performed concurrently: the receiver thread iterates server events through event iteration (events()/results()) to return the recognition results to the client in real time.We recommend that the duration of each audio segment sent is about 100 milliseconds, and the data size is between 1 KB and 16 KB.
-
End processing
Call the session's
stopmethod to stop speech recognition.This method only notifies the server that the input is complete; the receiver thread must continue to consume
events()until thetask-finishedevent to obtain the final recognition results and statistics. Errors at the WebSocket layer are raised asDashScopeErrorexceptions, which can be caught with try/except at the sending or receiving points.
Click to view the complete example
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
# China (Beijing): Replace {WorkspaceId} with your actual workspace ID. The configuration varies by region.
client = dashscope.Client(
# If you have not configured the API key in the environment variable, replace the following line with your API key: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="cn-beijing",
)
mic = None
stream = None
# Set recording parameters
sample_rate = 16000 # sampling rate (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__':
print('Initializing ...')
signal.signal(signal.SIGINT, signal_handler)
print("Press 'Ctrl+C' to stop recording and recognition...")
# Call recognition service, you can customize the recognition parameters, like model, format,
# sample_rate
with client.audio.asr.recognize(
model='paraformer-realtime-v2',
format=format_pcm,
# 'pcm', 'wav', 'opus', 'speex', 'aac', or 'amr'. You can check the supported formats in the document.
sample_rate=sample_rate,
# 8000 or 16000 is supported.
parameters={'semantic_punctuation_enabled': False},
) as recognition:
# Open the microphone
mic = pyaudio.PyAudio()
stream = mic.open(format=pyaudio.paInt16,
channels=1,
rate=16000,
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
# China (Beijing): Replace {WorkspaceId} with your actual workspace ID. The configuration varies by region.
client = dashscope.Client(
# If you have not configured the API key in the environment variable, replace the following line with your API key: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="cn-beijing",
)
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='paraformer-realtime-v2',
format='wav',
sample_rate=16000,
# The "language_hints" parameter is supported only by the paraformer-realtime-v2 model.
parameters={'language_hints': ['zh', 'en']},
) 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}"):
while True:
audio_data = f.read(3200)
if not audio_data:
break
else:
recognition.send_audio_frame(audio_data)
time.sleep(0.1)
else:
raise Exception(
'The supplied file was empty (zero bytes long)')
f.close()
recognition.stop()
receiver.result()
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,
))
Concurrent calls
In Python, because of the Global Interpreter Lock (GIL), only one thread can execute Python code at a time (although some performance-oriented libraries may remove this limitation). If you want to better utilize the computing resources of a multi-core computer, we recommend that you use multiprocessing or concurrent.futures.ProcessPoolExecutor. Multi-threading can significantly increase SDK call latency under high concurrency.
Request parameters
Request parameters are set through the recognize/recognize_file methods of the core resource (client.audio.asr): model, format, sample_rate, vocabulary_id, and disfluency_removal_enabled are named parameters, and the remaining parameters (such as language_hints and semantic_punctuation_enabled) are passed in through the parameters dictionary.
Parameter | Type | Default | Required | Description |
|---|---|---|---|---|
model | str | - | Yes | The model used for real-time speech recognition. For more information, see Model List. |
sample_rate | int | - | Yes | Set the sample rate (in Hz) of the audio to be recognized. Varies by model:
|
format | str | - | Yes | Set the audio format to be recognized. Supported audio formats: pcm, wav, mp3, opus, speex, aac, amr. opus/speex: Must use Ogg encapsulation. wav: Must be PCM encoded. amr: Only AMR-NB type is supported. |
vocabulary_id | str | - | 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. |
disfluency_removal_enabled | bool | False | No | Set whether to filter filler words:
|
language_hints | list[str] | ["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:
This parameter applies only to multilingual models. For more information, see Model list. |
semantic_punctuation_enabled | bool | False | No | Set whether to enable semantic segmentation. Disabled by default.
Semantic segmentation provides higher accuracy and is suitable for meeting transcription scenarios. VAD (Voice Activity Detection) segmentation has lower latency and is suitable for interactive scenarios. By adjusting the This parameter only takes effect when the model is v2 or later. |
max_sentence_silence | int | 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 |
multi_threshold_mode_enabled | bool | 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 |
punctuation_prediction_enabled | bool | True | No | Set whether to automatically add punctuation in the recognition results:
This parameter only takes effect when the model is v2 or later. |
heartbeat | bool | False | No | When you need to maintain a long connection with the server, use this switch to control the behavior:
This parameter only takes effect when the model is v2 or later. This field was introduced in SDK 1.23.1 and is already included in version 2.0.1 and later. |
inverse_text_normalization_enabled | bool | 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. |
Key interfaces
Core resource (client.audio.asr)
Real-time speech recognition is exposed through the client.audio.asr resource: recognize creates a bidirectional streaming recognition session (Recognition), and recognize_file recognizes a local file in one shot.
| Member method | Method signature | Description |
|---|---|---|
recognize | | Creates a bidirectional streaming recognition session. Entering the Sending audio and consuming events must be performed concurrently (use this 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 events one by one. The file to be recognized must have read permissions. |
start | | Starts speech recognition: establishes the connection, submits the task, and waits for |
send_audio_frame | | Pushes an audio stream. The audio stream pushed each time should not be too large or too small. We recommend that each audio packet has a duration of about 100 ms and a size between 1 KB and 16 KB. You can obtain the recognition results through event iteration ( |
stop | | Stops speech recognition: it only notifies the server that the input is complete. The receiver thread must continue to consume |
events / results | | Iterates server events: |
close | | Closes the recognition session. Automatically called when exiting the |
request_id / first_package_delay / last_package_delay | | Gets the request_id, the first packet delay (the latency from sending the first audio packet to receiving the first recognition result), and the last packet delay (the time taken from sending the |
Event iteration (events()/results())
During a bidirectional streaming call, the server returns key process information and data to the client through events. You need to iterate the session's events() (raw event dicts) or results() (typed recognition result frames) in a receiver thread to process the information and data returned by the server.
Click to view the example
# Iterate raw events: the recognized text is located 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('Recognized text: ', sentence['text'])
# Or iterate only recognition result frames (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('Recognized text: ', sentence['text'])
| Event/iteration method | Output | Return value | Description |
|---|---|---|---|
|
| None | Read internally by |
|
| Iterator | Yields an event whenever the server sends a response. The recognized text is located in |
|
| Iterator | Yields only recognition result frames (heartbeat frames filtered out). The iteration ends after all recognition results are returned. |
|
| None | Raised in the sending/receiving thread when an exception occurs. You can catch it with try/except. |
|
| None | Yielded by |
Response results
Recognition result (RecognitionResult)
RecognitionResult represents a recognition result frame yielded by iterating the session's results(). It can be used in both bidirectional streaming calls 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 currently recognized sentence and timestamp information. This method returns a Dict[str, Any] type (single-sentence information). For more information, see Sentence. |
request_id | | The request_id of the current event. |
is_sentence_end | | Determines whether the current sentence has ended ( |
Sentence (Sentence)
The members of the Sentence class are as follows:
Parameter | Type | Description |
|---|---|---|
begin_time | int | The start time of the sentence, in ms. |
end_time | int | The end time of the sentence, in ms. |
text | str | The recognized text. |
words | A list of Word timestamp information (Word) | Word timestamp information. |
emo_tag | str | The emotion of the current sentence:
Emotion recognition has the following constraints:
|
emo_confidence | float | The confidence level of the recognized emotion for the current sentence. The value ranges from 0.0 to 1.0. A larger value indicates a higher confidence level. Emotion recognition has the following constraints:
|
Word timestamp information (Word)
The members of the Word class are as follows:
Parameter | Type | Description |
|---|---|---|
begin_time | int | The start time of the word, in ms. |
end_time | int | The end time of the word, 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 to report your issue and provide the Request ID for further investigation.
More examples
For more examples, see GitHub.
FAQ
Features
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.
# Basic conversion command (universal template)
# -i: Input file path. Example: audio.wav
# -c:a: Audio codec. Example: aac, libmp3lame, pcm_s16le
# -b:a: Bitrate (quality control). Example: 192k, 320k
# -ar: Sample rate. Example: 44100 (CD), 48000, 16000
# -ac: Number of channels. Example: 1 (mono), 2 (stereo)
# -y: Overwrite existing file (no value needed)
ffmpeg -i input_audio.ext -c:a codec_name -b:a bitrate -ar sample_rate -ac channels output.ext
# Example: WAV -> MP3 (preserve original quality)
ffmpeg -i input.wav -c:a libmp3lame -q:a 0 output.mp3
# Example: MP3 -> WAV (16-bit PCM standard format)
ffmpeg -i input.mp3 -c:a pcm_s16le -ar 44100 -ac 2 output.wav
# Example: M4A -> AAC (extract/convert Apple audio)
ffmpeg -i input.m4a -c:a copy output.aac # Direct extraction without re-encoding
ffmpeg -i input.m4a -c:a aac -b:a 256k output.aac # Re-encode for higher quality
# Example: FLAC lossless -> Opus (high compression)
ffmpeg -i input.flac -c:a libopus -b:a 128k -vbr on output.opus
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 do I recognize a local file (recorded audio file)?
There are two ways to recognize a local file:
-
Directly pass the local file path: This method returns the complete recognition result after the file is fully processed. It is not suitable for scenarios that require immediate feedback.
Call the
recognize_filemethod of the core resource (client.audio.asr) with the file path to directly recognize the recorded audio file. For more information, see Non-streaming call. -
Convert the local file into a binary stream for recognition: This method returns recognition results as a stream while the file is being processed. It is suitable for scenarios that require immediate feedback.
You can use the
send_audio_framemethod of the recognition session to send a binary stream to the server for recognition. For more information, see bidirectional streaming call.
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 towav(incorrect parameter setting). - The audio sample rate is 3600 Hz, but the request parameter
sampleRate/sample_rateis set to 48000 (incorrect parameter setting).
You can use the ffprobe tool to obtain the container, codec, sample rate, channel, and other information about the audio:
- The audio file extension is .wav, but the actual format is MP3, and the request parameter
ffprobe -v error -show_entries format=format_name -show_entries stream=codec_name,sample_rate,channels -of default=noprint_wrappers=1 input.xxx
-
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, but
language_hintsis set toen(English). -
If all the above checks pass, you can use custom hot words to improve recognition accuracy for specific words.
Q: How do I fix missing recognition results caused by an incorrect audio format parameter?
format is required and must match the actual audio format. For example, for an MP3 audio file with a .wav extension, set format='mp3'.
-
Check the actual audio format: Use
ffprobeto inspect the audio container, codec, sample rate, and channels.ffprobe -v error -show_entries format=format_name -show_entries stream=codec_name,sample_rate,channels -of default=noprint_wrappers=1 your_audio_file -
Set the request parameters: Set
formatto the actual audio format. Setsample_rateto the actual sample rate and ensure that it meets the requirements of the model you use. -
Convert the audio format if needed: If you need WAV audio, use the following command to generate a PCM-encoded, 16 kHz, mono WAV file.
ffmpeg -i input_file -c:a pcm_s16le -ar 16000 -ac 1 output.wavAfter conversion, set
format='wav'andsample_rate=16000.
ImportantWhen you use format='wav', the audio must be a PCM-encoded WAV file.