Use the DashScope Python SDK to integrate CosyVoice real-time speech synthesis into your application through non-streaming, one-way streaming, or bidirectional streaming modes.
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.
- Singapore
- China (Beijing)
wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inferenceReplace {WorkspaceId} with your actual workspace ID.SpeechSynthesizer
Package path: dashscope.audio.tts_v2.SpeechSynthesizer
Constructor
call() - non-streaming
Method signature:
| Parameter | Type | Required | Description |
|---|---|---|---|
text | str | Yes | The full text to synthesize. Maximum length: 20,000 characters. |
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:
| 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. |
streaming_complete() - end streaming
Method signature:
streaming_cancel() - cancel streaming synthesis
Method signature:
| Parameter | Type | Required | Description |
|---|---|---|---|
complete_timeout_millis | int | No | Timeout in milliseconds for waiting for the server to return the task-finished event. Default value: 10000. |
SpeechSynthesizer instance.
get_last_request_id() - get request ID
Method signature:
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:
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:
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 | 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 dashscope.audio.tts_v2 and supports MP3, WAV, PCM, and other formats. |
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 mp3 or opus, use bit_rate to adjust the bit rate.Default value: 32.Valid values: [6, 510].Set bit_rate through the additional_params parameter: |
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, cosyvoice-v2, and system voices marked as supported in CosyVoice Voice list. Cloned voices of other models do not support this feature.Set word_timestamp_enabled through the additional_params parameter: |
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]. |
language_hints | list[str] | No | Specifies the target language for speech synthesis to improve output quality.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 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 cosyvoice-v3-flash, cosyvoice-v3-plus, cosyvoice-v2 support this feature. enable_aigc_tag, aigc_propagator, and aigc_propagate_id through the additional_params parameter: |
aigc_propagator | str | No | Sets the ContentPropagator field in the AIGC watermark, identifying the content propagator. Takes effect only when enable_aigc_tag is true.Default value: Alibaba Cloud UID.Only cosyvoice-v3-flash, cosyvoice-v3-plus, cosyvoice-v2 support this feature. additional_params parameter. See the enable_aigc_tag example. |
aigc_propagate_id | str | No | Sets the PropagateID field in the AIGC watermark, uniquely identifying a specific propagation action. Takes effect only when enable_aigc_tag is true.Default value: The request ID of the current speech synthesis request.Only cosyvoice-v3-flash, cosyvoice-v3-plus, cosyvoice-v2 support this feature. additional_params parameter. See the enable_aigc_tag example. |
hot_fix | dict | No | Configures pronunciation corrections and text replacements applied before synthesis. This feature isn't supported by cosyvoice-v2.
|
enable_markdown_filter | bool | No | Only cloned voices of cosyvoice-v3-flash support this feature.
enable_markdown_filter through the additional_params parameter: |
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:
on_event() - receive server response
Method signature:
| Parameter | Type | Required | Description |
|---|---|---|---|
message | str | Yes | A server response event in JSON format containing header (request information) and payload (output information). The payload.output field contains event type, original text, and other details. See output field in on_event messages. |
json.loads(message) and access payload.output for details.
on_complete() - synthesis complete
Method signature:
on_data() - receive audio data
Method signature:
| Parameter | Type | Required | Description |
|---|---|---|---|
data | bytes | Yes | A chunk of audio binary data in the format specified by the constructor's format parameter. |
on_error() - error occurred
Method signature:
| Parameter | Type | Required | Description |
|---|---|---|---|
message | str | Yes | An error description containing the error code and detailed reason. |
on_close() - connection closed
Method signature:
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: sentence-begin (sentence synthesis started), sentence-synthesis (sentence synthesis in progress), or sentence-end (sentence synthesis finished). |
original_text | str | The original text of the current sentence. Returned in sentence-begin and sentence-end events. |
sentence | dict | Sentence information. Contains index (sentence sequence number) and words (word list with timestamp information when word_timestamp_enabled is on). |
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.
- Non-streaming
- One-way streaming
- Bidirectional streaming
The text sent in a single call must not exceed 20,000 characters. Exceeding this limit causes an error.
- dashscope CLI