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.
Supported regions: Singapore and China North 2 (Beijing). Use an API key and endpoint from the region you call; see Regions and endpoints.
Requests are sent to the endpoint passed through the
Resource path:
Method signature:
Parameters:
Return value:
Method signature:
Parameters:
Return value:
Submits text in segments within a bidirectional streaming session (
Parameters:
Method signature:
Description: Notifies the server that all text has been sent. This call does not block the current thread; the receiving thread must continue to consume
Method signature:
Description: Cancels the current streaming speech synthesis task. After calling this method, the SDK immediately ends the current task. After cancellation, the current session can no longer send text; create a new session to continue synthesis.
The following parameters are set through the
Example 1 (Description):
Example 2 (Description):
Example 3 (Description):
Example 4 (Description):
Example 5 (Description):
Streaming synthesis no longer uses callback interfaces: audio and server events are received through the session's iteration methods.
Method signature:
Return value:
Method signature:
Return value: Yields both server response events (
When an error occurs during synthesis, the WebSocket layer raises a
The event
Message example:
Parsing example:
The SDK provides the key interfaces for speech synthesis and supports the following calling modes:
cosyvoice-v3.5-plus, cosyvoice-v3.5-flash, and cosyvoice-v2 are available only in China North 2 (Beijing); call them with the cn-beijing endpoint and a China North 2 (Beijing) API key.
Service endpoint
Requests are sent to the endpoint passed through the ws_url parameter of client.audio.tts.synthesize, stream, and connect. The following address is for Singapore (ap-southeast-1). For another region, replace ap-southeast-1 with the region code (for example, cn-beijing for China North 2 (Beijing)) and use an API key from that region. See Regions and endpoints.
wss://ap-southeast-1.maas.qwencloudapi.com/api-ws/v1/inference
Core resource (client.audio.tts)
Resource path: client.audio.tts
Description: WebSocket-based speech synthesis, providing three calling modes: one-shot synthesis (synthesize), streaming synthesis (stream), and bidirectional streaming session (connect).
Calling entry
synthesize() - 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 waits and returns the complete audio data at once. It is best suited for short text where strict real-time performance is not required. synthesize and stream create a new session for each call; there is no need to reuse instances.
stream() - streaming
Method signature:
| Parameter | Type | Required | Description |
|---|---|---|---|
text | str | Yes | The full text to synthesize. Maximum length: 20,000 characters. |
Iterator[bytes], the audio data yielded chunk by chunk.
Description: Streaming synthesis that sends the complete text at once and yields the audio chunk by chunk (Iterator[bytes]). It is best suited for short-text speech synthesis scenarios that require high real-time performance. To submit text in segments, use the bidirectional streaming session (connect).
send_text() - streaming input (session method)
Submits text in segments within a bidirectional streaming session (client.audio.tts.connect(...)).
Method signature:
text is the current text segment to synthesize. Call send_text multiple times to append text. Maximum per call: 20,000 characters; cumulative maximum: 200,000 characters. Sending text and receiving audio must run concurrently (use together with audio_chunks()/events() and stop).
stop() - end streaming input (session method)
Method signature:
audio_chunks()/events() 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.
cancel() - cancel streaming synthesis (session method)
Method signature:
Model limitations:
- China North 2 (Beijing): CosyVoice models require v2 or later.
- Singapore: CosyVoice models do not support this feature.
Session metrics and responses (session attributes)
first_package_delay:float, the delay in milliseconds from sending text to receiving the first audio chunk. Read this after synthesis completes.usage:dict, the usage information of the most recent synthesis task.last_response:dict, the response message of the most recent synthesis task (withheader/payloadkeys). The request_id of the most recent request can be obtained from theheaderofsession.last_response, which is useful for troubleshooting and log correlation.
Request parameters
The following parameters are set through the synthesize/stream/connect methods of client.audio.tts to control the model, voice, format, and audio characteristics (model, voice, format, sample_rate, volume, rate, pitch, language_hints, and enable_ssml are named parameters; ws_url specifies the regional endpoint; the remaining parameters are passed through the parameters dictionary).
| Parameter | Type | Required | Description |
|---|---|---|---|
model | str | Yes | The model name. |
voice | str | Yes | The voice used for speech synthesis.
|
format | str | No | Audio encoding format. Default value: mp3. Supports mp3, wav, pcm, and other formats. The sample rate is set through the sample_rate parameter, with a default of 22050. |
volume | int | No | The volume level. Default value: 50. Valid values: [0, 100]. |
rate | float | No | The speech rate. Default value: 1.0. Valid values: [0.5, 2.0]. |
pitch | 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 parameters dictionary: See Example 1 below |
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 parameters dictionary: See Example 2 below |
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 | Tip: - This parameter is an array, but the current version only processes the first element. Pass a single value.
|
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. Note: Only cosyvoice-v3-flash, cosyvoice-v3-plus, cosyvoice-v2 support this feature. Set enable_aigc_tag, aigc_propagator, and aigc_propagate_id through the parameters dictionary: See Example 3 below |
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: QwenCloud account ID. Note: Only cosyvoice-v3-flash, cosyvoice-v3-plus, cosyvoice-v2 support this feature. Set through the parameters dictionary. 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. Note: Only cosyvoice-v3-flash, cosyvoice-v3-plus, cosyvoice-v2 support this feature. Set through the parameters dictionary. See the enable_aigc_tag example. |
hot_fix | dict | No | Configures pronunciation corrections and text replacements applied before synthesis. Note: This feature isn't supported by cosyvoice-v2. Parameters:
|
enable_markdown_filter | bool | No | Note: 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:
enable_markdown_filter through the parameters dictionary: See Example 5 below |
Session and event iteration
Streaming synthesis no longer uses callback interfaces: audio and server events are received through the session's iteration methods. stream()/synthesize() require no session management; the lifecycle of a bidirectional streaming session (client.audio.tts.connect(...)) is: enter the with context to establish the connection automatically, call send_text() multiple times, call stop(), read all results, then exit the context to close the connection automatically.
audio_chunks() - iterate audio data
Method signature:
Iterator[bytes], the audio binary data yielded chunk by chunk, in the format specified by the format parameter.
Description: Iterate in the receiving thread to receive the audio data chunk by chunk; multiple chunks are yielded during synthesis. Write the data to a file or feed it to a playback device. A session allows only one reader of events() or audio_chunks().
events() - iterate server events
Method signature:
dict, containing header (request information) and payload (output information)) and audio bytes. The payload.output field contains the event type, original text, and other information. See output field in events() messages.
Description: Iterate over the server responses in the receiving thread. The responses contain the output information of synthesis events (event type, original text, sentence information, etc.); access payload.output directly for details.
Error handling
When an error occurs during synthesis, the WebSocket layer raises a DashScopeError exception, and the connection is closed automatically after the exception is raised. Use try/except at the sending/receiving side to catch and log errors for troubleshooting:
Session lifecycle
- The connection is established automatically when entering the
withcontext (you can initialize audio output streams or open file resources beforehand). - After all text is synthesized and all audio data has been yielded, the
events()/audio_chunks()iteration ends; after that, you can read performance metrics such asfirst_package_delay. - The connection is closed automatically when exiting the
withcontext (you can release audio playback devices and other resources afterwards).
output field in events() messages
The event dict yielded by the session events() iterator 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 provides the key interfaces for speech synthesis and supports the following calling modes:
- Non-streaming: A blocking call that sends the complete text at once and returns the complete audio directly. Best suited for short-text speech synthesis.
- Unidirectional streaming: A non-blocking call that sends the complete text at once and receives the data by iterating the audio chunks yielded by
stream. Best suited for short-text speech synthesis that requires high real-time performance. - Bidirectional streaming: A non-blocking call that sends text in multiple segments and receives the incrementally synthesized audio stream in real time by iterating the session's
audio_chunks()/events(). Best suited for long-text speech synthesis that requires high real-time performance.
- Non-streaming
- One-way streaming
- Bidirectional streaming