Skip to main content
SDK access

CosyVoice Python SDK

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. 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

# Singapore (ap-southeast-1). For another region, replace ap-southeast-1 in the URL.
# API keys are region-specific. See https://docs.qwencloud.com/developer-guides/getting-started/regions
ws_url = "wss://ap-southeast-1.maas.qwencloudapi.com/api-ws/v1/inference"

# One-shot synthesis: returns the complete audio bytes
audio = client.audio.tts.synthesize(
    "How is the weather today?",   # text is a required positional argument
    model="cosyvoice-v3-plus",     # The model that the voice belongs to
    voice="longanyang",            # The voice
    format="mp3",                  # Audio encoding format, default "mp3"
    sample_rate=22050,             # Sample rate, default 22050
    ws_url=ws_url,
)

# Streaming synthesis: yields audio bytes chunk by chunk (write/play while receiving)
for chunk in client.audio.tts.stream(
        "How is the weather today?", model="cosyvoice-v3-plus", voice="longanyang", ws_url=ws_url):
    ...

# Bidirectional streaming session: send text in segments; the connection is established automatically when entering the with context
with client.audio.tts.connect(model="cosyvoice-v3-plus", voice="longanyang", ws_url=ws_url) as session:
    session.send_text("How is the weather today?")    # Can be called multiple times to append text
    session.stop()                                     # Notify the server that the input is complete
    for chunk in session.audio_chunks():
        ...

synthesize() - non-streaming

Method signature:
def synthesize(self,
               text: str,
               *,
               model: str = "cosyvoice-v1",
               voice: str = "longxiaochun",
               format: str = "mp3",
               sample_rate: int = 22050,
               volume: int = None,
               rate: float = None,
               pitch: float = None,
               language_hints: list = None,
               enable_ssml: bool = None,
               parameters: Dict = None,
               ...) -> bytes
Parameters:
ParameterTypeRequiredDescription
textstrYesThe full text to synthesize. Maximum length: 20,000 characters.
Return value: 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:
def stream(self,
           text: str,
           *,
           model: str,
           voice: str,
           format: str = "mp3",
           sample_rate: int = 22050,
           ...) -> Iterator[bytes]
Parameters:
ParameterTypeRequiredDescription
textstrYesThe full text to synthesize. Maximum length: 20,000 characters.
Return value: 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:
def send_text(self, text: str) -> None
Parameters: 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:
def stop(self) -> None
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 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:
def cancel(self) -> None
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.
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)

session.first_package_delay
session.usage
session.last_response
  • 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 (with header/payload keys). The request_id of the most recent request can be obtained from the header of session.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).
ParameterTypeRequiredDescription
modelstrYesThe model name.
voicestrYesThe voice used for speech synthesis.
  • System voices: See CosyVoice Voice list
  • Cloned voices: Custom voices created through voice cloning
  • Custom voices: Custom voices created through voice design
formatstrNoAudio 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.
volumeintNoThe volume level. Default value: 50. Valid values: [0, 100].
ratefloatNoThe speech rate. Default value: 1.0. Valid values: [0.5, 2.0].
pitchfloatNoThe pitch. Default value: 1.0. Valid values: [0.5, 2.0].
bit_rateintNoThe 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_enabledboolNoSpecifies 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
seedintNoA 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_hintslist[str]NoTip: - This parameter is an array, but the current version only processes the first element. Pass a single value.
  • This parameter specifies the target language for speech synthesis. It's unrelated to the language of the audio sample used in voice cloning. To set the source language for a cloning task, see the voice cloning API reference.
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:
  • Unexpected digit pronunciation: "hello, this is 110" is read as "hello, this is one zero" instead of the expected Chinese pronunciation
  • Inaccurate symbol pronunciation: "@" is read as the Chinese equivalent instead of "at"
  • Poor minor language synthesis quality with unnatural results
  • zh: Chinese
  • en: English
  • fr: French
  • de: German
  • ja: Japanese
  • ko: Korean
  • ru: Russian
  • pt: Portuguese
  • th: Thai
  • id: Indonesian
  • vi: Vietnamese
  • es: Spanish
  • it: Italian
  • ms: Malaysian
  • fil: Filipino
  • ar: Arabic
instructionstrNoControls synthesis characteristics such as dialect, emotion, or speaking style. For usage details, see Instruction control.
enable_aigc_tagboolNoSpecifies 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_propagatorstrNoSets 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_idstrNoSets 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_fixdictNoConfigures pronunciation corrections and text replacements applied before synthesis. Note: This feature isn't supported by cosyvoice-v2. Parameters:
  • pronunciation: Custom pronunciation. Specifies pinyin annotations for words to correct inaccurate default pronunciations.
  • replace: Text replacement. Replaces specified words with target text before synthesis. The replaced text is used as the actual synthesis input.
Example: See Example 4 below
enable_markdown_filterboolNoNote: 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:
  • true: Enable Markdown filtering
  • false: Disable Markdown filtering
Set enable_markdown_filter through the parameters dictionary: See Example 5 below
Example 1 (Description):
audio = client.audio.tts.synthesize(
    "Text to synthesize",
    model="cosyvoice-v3-plus",
    voice="longanyang",
    parameters={"bit_rate": 128},
)
Example 2 (Description):
audio = client.audio.tts.stream(
    "Text to synthesize",
    model="cosyvoice-v3-flash",
    voice="your_voice",  # A system voice or cloned voice that supports word-level timestamps
    parameters={"word_timestamp_enabled": True},
)
Example 3 (Description):
audio = client.audio.tts.synthesize(
    "Text to synthesize",
    model="cosyvoice-v3-plus",
    voice="longanyang",
    parameters={
        "enable_aigc_tag": True,
        "aigc_propagator": "your_propagator",
        "aigc_propagate_id": "your_propagate_id"
    },
)
Example 4 (Description):
audio = client.audio.tts.synthesize(
    "Text to synthesize",
    model="cosyvoice-v3-plus",
    voice="your_voice",  # Voice
    parameters={
        "hot_fix": {
            "pronunciation": [{"weather": "tian1 qi4"}],
            "replace": [{"today": "gold day"}]
        }
    },
)
Example 5 (Description):
audio = client.audio.tts.synthesize(
    "Text to synthesize",
    model="cosyvoice-v3-flash",
    voice="your_voice",  # A cloned voice of cosyvoice-v3-flash
    parameters={"enable_markdown_filter": True},
)

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:
def audio_chunks(self) -> Iterator[bytes]
Return value: 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:
def events(self) -> Generator[Union[Dict, bytes], None, None]
Return value: Yields both server response events (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:
from dashscope import DashScopeError

try:
    ...
except DashScopeError as e:
    print(e.code, e.message, e.request_id)

Session lifecycle

  • The connection is established automatically when entering the with context (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 as first_package_delay.
  • The connection is closed automatically when exiting the with context (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:
FieldTypeDescription
typestrEvent type. Values: sentence-begin (sentence synthesis started), sentence-synthesis (sentence synthesis in progress), or sentence-end (sentence synthesis finished).
original_textstrThe original text of the current sentence. Returned in sentence-begin and sentence-end events.
sentencedictSentence information. Contains index (sentence sequence number) and words (word list with timestamp information when word_timestamp_enabled is on).
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:
def handle_event(event):
    output = (event.get('payload') or {}).get('output') or {}
    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 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
The text sent in a single call must not exceed 20,000 characters. Exceeding this limit raises a DashScopeError exception.
synthesize and stream create a new session for each call; there is no need to reuse instances.
# coding=utf-8

import os

import dashscope

# If the environment variable is not configured, replace the following line with your QwenCloud API Key: api_key="sk-xxx"
client = dashscope.Client(api_key=os.environ.get('DASHSCOPE_API_KEY'))

# Singapore (ap-southeast-1). For another region, replace ap-southeast-1 in the URL.
# API keys are region-specific. See https://docs.qwencloud.com/developer-guides/getting-started/regions
ws_url = "wss://ap-southeast-1.maas.qwencloudapi.com/api-ws/v1/inference"

# Model
model = "cosyvoice-v3-plus"
# Voice
voice = "longanyang"

# Send the text to synthesize and get the binary audio
audio = client.audio.tts.synthesize("How is the weather today?", model=model, voice=voice, ws_url=ws_url)

# Save the audio to a local file
with open('output.mp3', 'wb') as f:
    f.write(audio)
  • dashscope CLI
Call via the dashscope command line.
export DASHSCOPE_API_KEY="your-api-key"
# China North 2 (Beijing). This model is available only in this region.
# API keys are region-specific. See https://docs.qwencloud.com/developer-guides/getting-started/regions
export DASHSCOPE_HTTP_BASE_URL="https://cn-beijing.maas.qwencloudapi.com/api/v1"
dashscope speech-synthesis create -m cosyvoice-v3-plus -t "Hello world" --voice longanyang