Use the DashScope Python SDK to integrate Qwen-Audio-TTS/CosyVoice real-time speech synthesis into your application through non-streaming, one-way streaming, or bidirectional streaming modes.
User guide: For model descriptions and selection recommendations, see Speech synthesis.
Service endpoint
The SDK uses the Beijing region endpoint by default. To switch to a different region, modify dashscope.base_websocket_api_url before initialization.
China (Beijing)
wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference
Replace {WorkspaceId} with your actual workspace ID.
Singapore
wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference
Replace {WorkspaceId} with your actual workspace ID.
Switch to the Singapore region:
import dashscope
# Set at the beginning of your code
dashscope.base_websocket_api_url = 'wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference'
Alibaba Cloud Model Studio has released workspace-specific domains for the China (Beijing) and Singapore regions. The new dedicated domains deliver superior performance and higher stability for inference requests. We recommend migrating to the new domains:
China (Beijing): from
dashscope.aliyuncs.comto{WorkspaceId}.cn-beijing.maas.aliyuncs.comSingapore: from
dashscope-intl.aliyuncs.comto{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
Replace {WorkspaceId} with your actual Workspace ID. The existing domains remain fully functional.
SpeechSynthesizer
Package path: dashscope.audio.tts_v2.SpeechSynthesizer
Constructor
SpeechSynthesizer(
model: str,
voice: str,
format: AudioFormat = AudioFormat.MP3_22050HZ_MONO_256KBPS,
volume: int = 50,
speech_rate: float = 1.0,
pitch_rate: float = 1.0,
callback: ResultCallback = None)
call() - non-streaming
Method signature:
def call(self, text: str) -> bytes
Parameters:
|
Parameter |
Type |
Required |
Description |
|
text |
str |
Yes |
The full text to synthesize. Maximum length: 20,000 characters. |
Return value: bytes containing the complete audio data.
Description: This blocking call returns the complete audio data at once. It is best suited for short text where real-time streaming is not required. Reinitialize the SpeechSynthesizer instance before each call.
streaming_call() - streaming
Method signature:
def streaming_call(self, text: str) -> None
Parameters:
|
Parameter |
Type |
Required |
Description |
|
text |
str |
Yes |
A text segment to synthesize. Call this method multiple times to append text. Maximum per call: 20,000 characters. Cumulative maximum: 200,000 characters. |
Description: This bidirectional streaming call accepts text in segments and delivers synthesized audio through callbacks in real time. It is ideal for integration with large language models where text is generated progressively. Call streaming_complete() after sending all text.
streaming_complete() - end streaming
Method signature:
def streaming_complete(self) -> None
Description: Notifies the server that all text has been sent. Blocks the current thread until the remaining text is synthesized and all audio data is returned. Failing to call this method may result in trailing text not being converted to speech.
get_last_request_id() - get request ID
Method signature:
def get_last_request_id(self) -> str
Return value: str containing the request ID of the most recent request. Use this for troubleshooting and tracing.
get_first_package_delay() - get first-packet latency
Method signature:
def get_first_package_delay(self) -> int
Return value: int representing the delay in milliseconds from sending text to receiving the first audio chunk. Call this after synthesis completes.
get_response() - get response message
Method signature:
def get_response(self) -> str
Return value: str containing the JSON-formatted response message from the most recent synthesis task, including request status and output information.
Constructor parameters
The following parameters are set through the SpeechSynthesizer constructor to control the model, voice, format, and audio characteristics.
|
Parameter |
Type |
Required |
Description |
|
model |
str |
Yes |
The model name. |
|
voice |
str |
Yes |
voice The voice used for speech synthesis.
|
|
format |
enum |
No |
Audio encoding format and sample rate.
Default: AudioFormat.MP3_22050HZ_MONO_256KBPS. The AudioFormat enum is located in |
|
volume |
int |
No |
The volume level. Default value: 50. Valid values: [0, 100]. |
|
speech_rate |
float |
No |
The speech rate. Default value: 1.0. Valid values: [0.5, 2.0]. |
|
pitch_rate |
float |
No |
The pitch. Default value: 1.0. Valid values: [0.5, 2.0]. |
|
bit_rate |
int |
No |
The audio bit rate in kbps. When the audio format is opus, use Default value: 32. Valid values: [6, 510].
Note
Set
|
|
word_timestamp_enabled |
bool |
No |
Specifies whether to enable word-level timestamps. Default value: false. Available only in streaming output mode. Supported voices: cloned voices of cosyvoice-v3.5-plus, cosyvoice-v3.5-flash, cosyvoice-v3-flash, cosyvoice-v3-plus, and cosyvoice-v2, and system voices marked as supported in CosyVoice Voice list. qwen-audio-3.0-tts-plus, qwen-audio-3.0-tts-flash, and cloned voices of other models do not support this feature. Note
Set
|
|
seed |
int |
No |
A random seed for controlling variation in the synthesis output. When the model version, text, voice, and other parameters are unchanged, using the same seed produces identical results. Default value: 0. Valid values: [0, 65535]. cosyvoice-v1 doesn't support this parameter. |
|
language_hints |
list[str] |
No |
Important
Specifies the target language for speech synthesis to improve output quality. cosyvoice-v1 doesn't support this feature. When digit pronunciation, abbreviation expansion, symbol reading, or minority-language synthesis doesn't meet expectations, use this parameter. For example:
Valid values:
|
|
instruction |
str |
No |
Controls synthesis characteristics such as dialect, emotion, or speaking style. For usage details, see Instruction-based control. |
|
enable_aigc_tag |
bool |
No |
Specifies whether to embed an AIGC watermark in the generated audio. When set to true, the watermark is embedded in audio files of supported formats (wav/mp3/opus). Default value: false. Only qwen-audio-3.0-tts-plus, qwen-audio-3.0-tts-flash, cosyvoice-v3-flash, cosyvoice-v3-plus, and cosyvoice-v2 support this feature. Note
Set
|
|
aigc_propagator |
str |
No |
Sets the Default value: Alibaba Cloud UID. Only qwen-audio-3.0-tts-plus, qwen-audio-3.0-tts-flash, cosyvoice-v3-flash, cosyvoice-v3-plus, and cosyvoice-v2 support this feature. Set through the |
|
aigc_propagate_id |
str |
No |
Sets the Default value: The request ID of the current speech synthesis request. Only qwen-audio-3.0-tts-plus, qwen-audio-3.0-tts-flash, cosyvoice-v3-flash, cosyvoice-v3-plus, and cosyvoice-v2 support this feature. Set through the |
|
hot_fix |
dict |
No |
Configures pronunciation corrections and text replacements applied before synthesis. This feature isn't supported by qwen-audio-3.0-tts-plus, qwen-audio-3.0-tts-flash, cosyvoice-v2, or cosyvoice-v1. Parameters:
Example:
|
|
enable_markdown_filter |
bool |
No |
Important
Only cloned voices of cosyvoice-v3-flash support this feature. Specifies whether to enable Markdown filtering. When enabled, the system automatically strips Markdown markup symbols from the input text before synthesis, preventing them from being read aloud. Default value: false. Valid values:
Note
Set
|
|
callback |
ResultCallback |
No |
A callback instance for receiving synthesized audio and event notifications asynchronously. When set, call() runs in streaming mode and delivers audio through the on_data callback. When not set, call() runs in non-streaming mode and returns the complete audio as bytes. |
ResultCallback
Package path: dashscope.audio.tts_v2.ResultCallback
on_open() - connection established
Method signature:
def on_open(self) -> None
Triggered when: The WebSocket connection is successfully established. Use this callback to initialize audio output streams or open file resources.
on_event() - receive server response
Method signature:
def on_event(self, message: str) -> None
Parameters:
|
Parameter |
Type |
Required |
Description |
|
message |
str |
Yes |
A server response event in JSON format containing |
Triggered when: A server response is received. The message is a JSON string containing synthesis event output (event type, original text, sentence information). Parse with json.loads(message) and access payload.output for details.
on_complete() - synthesis complete
Method signature:
def on_complete(self) -> None
Triggered when: All text has been synthesized and all audio data has been delivered through on_data. Use this callback to call get_first_package_delay() for performance metrics.
on_data() - receive audio data
Method signature:
def on_data(self, data: bytes) -> None
Parameters:
|
Parameter |
Type |
Required |
Description |
|
data |
bytes |
Yes |
A chunk of audio binary data in the format specified by the constructor's format parameter. |
Triggered when: An audio data chunk is received. This callback is invoked multiple times during synthesis. Use it to write data to a file or feed it to a playback device.
on_error() - error occurred
Method signature:
def on_error(self, message: str) -> None
Parameters:
|
Parameter |
Type |
Required |
Description |
|
message |
str |
Yes |
An error description containing the error code and detailed reason. |
Triggered when: An error occurs during synthesis. The connection closes automatically after this callback fires. Log the error for troubleshooting.
on_close() - connection closed
Method signature:
def on_close(self) -> None
Triggered when: The WebSocket connection closes (whether normally or due to an error). Use this callback to release resources such as audio playback devices.
output field in on_event messages
The JSON message received by the on_event callback contains a payload.output field with synthesis event information. Use this field to track synthesis progress and retrieve per-sentence details. The output field structure is as follows:
|
Field |
Type |
Description |
|
type |
str |
Event type. Values: |
|
original_text |
str |
The original text of the current sentence. Returned in |
|
sentence |
dict |
Sentence information. Contains |
Message example:
{
"header": {
"task_id": "xxx",
"event": "result-generated",
"attributes": {}
},
"payload": {
"output": {
"type": "sentence-begin",
"original_text": "How is the weather today?",
"sentence": {
"index": 0,
"words": []
}
}
}
}
Parsing example:
import json
def on_event(self, message):
data = json.loads(message)
output = data.get('payload', {}).get('output', {})
event_type = output.get('type', '')
original_text = output.get('original_text', '')
if event_type:
print(f'Event type: {event_type}, Original text: {original_text}')
Code examples
The SDK supports the following synthesis modes:
-
Non-streaming: A blocking call that sends the complete text at once and returns the full audio directly. Best suited for short-text speech synthesis.
-
Unidirectional streaming: A non-blocking call that sends the complete text at once and delivers audio data (potentially in chunks) through a callback function. Best suited for short-text scenarios that require low latency.
-
Bidirectional streaming: A non-blocking call that sends text in multiple segments and delivers incrementally synthesized audio through a callback function in real time. Best suited for long-text scenarios that require low latency.
For more examples, see GitHub.
Non-streaming
The text sent in a single call must not exceed 20,000 characters. Exceeding this limit causes an error.
Reinitialize the SpeechSynthesizer instance before each call.
# coding=utf-8
import dashscope
from dashscope.audio.tts_v2 import *
import os
# The API Keys for Singapore and Beijing regions are different. Get API Key: https://help.aliyun.com/zh/model-studio/get-api-key
# If environment variable is not configured, replace the following line with your Model Studio API Key: dashscope.api_key = "sk-xxx"
dashscope.api_key = os.environ.get('DASHSCOPE_API_KEY')
# The following configuration is for the China (Beijing) region. Replace "{WorkspaceId}" with your actual workspace ID. The configuration varies by region.
dashscope.base_websocket_api_url='wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference'
# Model
model = "qwen-audio-3.0-tts-flash"
# Voice
voice = "longanlingxi"
# Instantiate SpeechSynthesizer, passing request parameters such as model and voice in the constructor
synthesizer = SpeechSynthesizer(model=model, voice=voice)
# Send text for synthesis and get binary audio
audio = synthesizer.call("How is the weather today?")
# The first text submission requires establishing a WebSocket connection, so the first packet latency includes the connection setup time
print('[Metric] requestId: {}, first packet latency: {} ms'.format(
synthesizer.get_last_request_id(),
synthesizer.get_first_package_delay()))
# Save audio to local file
with open('output.mp3', 'wb') as f:
f.write(audio)One-way streaming
The text sent in a single call must not exceed 20,000 characters. Exceeding this limit causes an error.
Reinitialize the SpeechSynthesizer instance before each call.
# coding=utf-8
import os
import json
import dashscope
from dashscope.audio.tts_v2 import *
from datetime import datetime
def get_timestamp():
now = datetime.now()
formatted_timestamp = now.strftime("[%Y-%m-%d %H:%M:%S.%f]")
return formatted_timestamp
# The API Keys for Singapore and Beijing regions are different. Get API Key: https://help.aliyun.com/zh/model-studio/get-api-key
# If environment variable is not configured, replace the following line with your Model Studio API Key: dashscope.api_key = "sk-xxx"
dashscope.api_key = os.environ.get('DASHSCOPE_API_KEY')
# The following configuration is for the China (Beijing) region. Replace "{WorkspaceId}" with your actual workspace ID. The configuration varies by region.
dashscope.base_websocket_api_url='wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference'
# Model
model = "qwen-audio-3.0-tts-flash"
# Voice
voice = "longanlingxi"
# Define callback interface
class Callback(ResultCallback):
_player = None
_stream = None
def on_open(self):
self.file = open("output.mp3", "wb")
print("Connection established: " + get_timestamp())
def on_complete(self):
print("Speech synthesis completed, all results received: " + get_timestamp())
# After the task completes (on_complete callback triggered), you can call get_first_package_delay to get the latency
# The first text submission requires establishing a WebSocket connection, so the first packet latency includes the connection setup time
print('[Metric] requestId: {}, first packet latency: {} ms'.format(
synthesizer.get_last_request_id(),
synthesizer.get_first_package_delay()))
def on_error(self, message: str):
print(f"Speech synthesis error: {message}")
def on_close(self):
print("Connection closed: " + get_timestamp())
self.file.close()
def on_event(self, message):
# Parse server-side events and get output information
data = json.loads(message)
output = data.get('payload', {}).get('output', {})
event_type = output.get('type', '')
original_text = output.get('original_text', '')
if event_type:
print(f"Event type: {event_type}, original text: {original_text}")
def on_data(self, data: bytes) -> None:
print(get_timestamp() + " Binary audio length: " + str(len(data)))
self.file.write(data)
callback = Callback()
# Instantiate SpeechSynthesizer, passing request parameters such as model and voice in the constructor
synthesizer = SpeechSynthesizer(
model=model,
voice=voice,
callback=callback,
)
# Send text for synthesis and get binary audio in real time via the on_data callback method
synthesizer.call("How is the weather today?")Bidirectional streaming
The text sent per call must not exceed 20,000 characters. The cumulative text must not exceed 200,000 characters.
-
During streaming input, call
streaming_callmultiple times to submit text segments in sequence. The server automatically performs sentence segmentation on received text:-
Complete sentences are synthesized immediately
-
Incomplete sentences are buffered until complete
When
streaming_completeis called, the server force-synthesizes all received but unprocessed text (including incomplete sentences). -
-
The interval between text segments must not exceed 23 seconds. Otherwise, a "request timeout after 23 seconds" exception is raised.
If there's no text to send, call
streaming_completepromptly to end the task.ImportantAlways call
streaming_complete. Failing to do so may cause trailing text to not be converted to speech.The server enforces a 23-second timeout. This value can't be modified on the client side.
# coding=utf-8
#
# pyaudio installation instructions:
# For macOS, run the following commands:
# brew install portaudio
# pip install pyaudio
# For Debian/Ubuntu, run the following commands:
# sudo apt-get install python-pyaudio python3-pyaudio
# or
# pip install pyaudio
# For CentOS, run the following commands:
# sudo yum install -y portaudio portaudio-devel && pip install pyaudio
# For Microsoft Windows, run the following command:
# python -m pip install pyaudio
import os
import time
import pyaudio
import json
import dashscope
from dashscope.api_entities.dashscope_response import SpeechSynthesisResponse
from dashscope.audio.tts_v2 import *
from datetime import datetime
def get_timestamp():
now = datetime.now()
formatted_timestamp = now.strftime("[%Y-%m-%d %H:%M:%S.%f]")
return formatted_timestamp
# The API Keys for Singapore and Beijing regions are different. Get API Key: https://help.aliyun.com/zh/model-studio/get-api-key
# If environment variable is not configured, replace the following line with your Model Studio API Key: dashscope.api_key = "sk-xxx"
dashscope.api_key = os.environ.get('DASHSCOPE_API_KEY')
# The following configuration is for the China (Beijing) region. Replace "{WorkspaceId}" with your actual workspace ID. The configuration varies by region.
dashscope.base_websocket_api_url='wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference'
# Model
model = "qwen-audio-3.0-tts-flash"
# Voice
voice = "longanlingxi"
# Define callback interface
class Callback(ResultCallback):
_player = None
_stream = None
def on_open(self):
print("Connection established: " + get_timestamp())
self._player = pyaudio.PyAudio()
self._stream = self._player.open(
format=pyaudio.paInt16, channels=1, rate=22050, output=True
)
def on_complete(self):
print("Speech synthesis completed, all results received: " + get_timestamp())
def on_error(self, message: str):
print(f"Speech synthesis error: {message}")
def on_close(self):
print("Connection closed: " + get_timestamp())
# Stop the player
self._stream.stop_stream()
self._stream.close()
self._player.terminate()
def on_event(self, message):
# Parse server-side events and get output information
data = json.loads(message)
output = data.get('payload', {}).get('output', {})
event_type = output.get('type', '')
original_text = output.get('original_text', '')
if event_type:
print(f"Event type: {event_type}, original text: {original_text}")
def on_data(self, data: bytes) -> None:
print(get_timestamp() + " Binary audio length: " + str(len(data)))
self._stream.write(data)
callback = Callback()
test_text = [
"Streaming text-to-speech SDK,",
"converts input text",
"into binary audio data.",
"Compared with non-streaming speech synthesis,",
"streaming synthesis offers better real-time performance.",
"Users hear near-synchronous audio output while typing,",
"greatly improving interaction experience",
"and reducing wait time.",
"Ideal for large language model (LLM) integration,",
"where text is streamed for speech synthesis.",
]
# Instantiate SpeechSynthesizer, passing request parameters such as model and voice in the constructor
synthesizer = SpeechSynthesizer(
model=model,
voice=voice,
format=AudioFormat.PCM_22050HZ_MONO_16BIT,
callback=callback,
)
# Send text for streaming synthesis. Get binary audio in real time via the on_data callback method
for text in test_text:
synthesizer.streaming_call(text)
time.sleep(0.1)
# End streaming speech synthesis
synthesizer.streaming_complete()
# The first text submission requires establishing a WebSocket connection, so the first packet latency includes the connection setup time
print('[Metric] requestId: {}, first packet latency: {} ms'.format(
synthesizer.get_last_request_id(),
synthesizer.get_first_package_delay()))