Non-real-time speech synthesis CosyVoice Python SDK reference
Use the CosyVoice non-real-time speech synthesis Python SDK to generate audio from text in non-streaming or streaming mode.
ImportantThe features described in this document are available only in the China (Beijing) region.
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.
Prerequisites
- Obtain an API key completed, and API key configured as an environment variable.
- DashScope Python SDK 2.0.1 or later installed. Install the latest version.
Core resource (client.audio.tts.http)
Resource path: client.audio.tts.http
Description: HTTP-based speech synthesis. The synthesize method performs a non-streaming call (audio is returned as a URL), and the stream method performs a streaming call (audio data is returned chunk by chunk over SSE).
synthesize() / stream() - speech synthesis
Method signature:
def synthesize(self,
text: str,
*,
model: str,
voice: str,
format: str = None,
sample_rate: int = None,
language_type: str = None,
parameters: Dict = None,
extra_input: Dict = None,
timeout: float = None,
...) -> HttpSynthesis
def stream(self,
text: str,
*,
model: str,
voice: str,
format: str = None,
sample_rate: int = None,
language_type: str = None,
parameters: Dict = None,
extra_input: Dict = None,
timeout: float = None,
...) -> HttpSynthesisStream
Parameters (model, text, voice, format, and sample_rate are named parameters; pass other input parameters via the extra_input dictionary):
| Parameter | Type | Required | Description |
|---|---|---|---|
model | str | Yes | The speech synthesis model. Valid values:
|
text | str | Yes | The text to synthesize. Supports SSML and LaTeX input. Replace the text content with the corresponding format.
|
voice | str | Yes | The voice for synthesis. Valid values:
|
format | str | No | The audio format. Default value: mp3. Valid values:
|
sample_rate | int | No | The audio sample rate in Hz. Valid values: 8000, 16000, 22050 (default), 24000, 44100, 48000. |
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 bitrate in kbps. Default value: 32. Valid values: [6, 510]. ImportantThis parameter is supported only when |
enable_ssml | bool | No | Specifies whether to enable SSML. Set this to True when text uses SSML format. Default: False. For supported SSML tags and usage, see SSML. For the SSML usage restrictions (supported models, voices, and APIs), see Limitations. |
word_timestamp_enabled | bool | No | Specifies whether to enable word-level timestamps. Default: 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. |
seed | int | No | The random seed for synthesis. Different seeds produce different outputs. With identical model version, text, voice, and other parameters, the same seed reproduces the same output. Default value: 0. Valid values: [0, 65535]. |
language_hints | list | No | Important
Specifies the target language for speech synthesis to improve output quality. Use this parameter when numbers, abbreviations, or symbols are not pronounced as expected, or when synthesis quality for secondary languages is poor. Examples:
Valid values
|
instruction | str | No | An instruction that controls the synthesis behavior, such as dialect, emotion, or role. For usage details, see Non-real-time speech synthesis. |
enable_aigc_tag | bool | No | Specifies whether to embed an AIGC watermark in the generated audio. When set to True, a watermark is embedded in audio files of supported formats (wav/mp3/opus). Default: False. NoteOnly cosyvoice-v3-flash, cosyvoice-v3-plus, cosyvoice-v2 support this feature. |
aigc_propagator | str | No | Sets the ContentPropagator field in the AIGC watermark to identify the content distributor. Takes effect only when enable_aigc_tag is True.Default: Alibaba Cloud UID. NoteOnly cosyvoice-v3-flash, cosyvoice-v3-plus, cosyvoice-v2 support this feature. |
aigc_propagate_id | str | No | Sets the PropagateID field in the AIGC watermark to uniquely identify a specific distribution action. Takes effect only when enable_aigc_tag is True.Default: The request ID of the current speech synthesis request. NoteOnly cosyvoice-v3-flash, cosyvoice-v3-plus, cosyvoice-v2 support this feature. |
hot_fix | dict | No | Text hot-fix configuration. Customizes the pronunciation of specified words or substitutes text before speech synthesis. NoteNot supported by cosyvoice-v2. Parameters:
Example: |
enable_markdown_filter | bool | No | Specifies whether to enable Markdown filtering. When enabled, the system automatically strips Markdown markup from the input text before synthesis, preventing markup symbols from being read aloud. NoteOnly cloned voices of cosyvoice-v3-flash support this feature. Default: False. Valid values:
|
Return values:
-
Non-streaming mode (
synthesize): Returns a result object (HttpSynthesis) with the following properties:audio_url: The audio download URL (expires after a limited time).audio_id: The audio ID.expires_at: The URL expiration time.usage: Usage information.
-
Streaming mode (
stream): Returns an iterator (HttpSynthesisStream). Each element (HttpSynthesisChunk) contains the following properties:audio: The audio binary data (bytes) for the current chunk, already decoded.sentence: Sentence-level synthesis information (if available).is_final: Indicates whether this is the final chunk (finish_reason == "stop").usage: Usage information (carried on the final chunk).
ImportantIn streaming mode, the final chunk (
is_finalisTrue) additionally carriesaudio_url(the download URL of the complete audio),audio_id, andexpires_at. When concatenating audio from the iterator, write only chunks with non-emptychunk.audioto avoid playing the same content twice.
Sample code
The following examples show non-streaming and streaming calls to CosyVoice speech synthesis. Set the DASHSCOPE_API_KEY environment variable before running the code.
NoteDifferent model versions require matching voice versions. For example, cosyvoice-v3-flash and cosyvoice-v3-plus use voices such as longanhuan, while cosyvoice-v2 uses voices such as longxiaochun_v2. When switching models, update the voice accordingly. Each voice supports different languages. To synthesize non-Chinese audio, select a voice that supports the target language. For the full mapping of models to voices, see CosyVoice Voice list.
Non-streaming call
A non-streaming call uses the synthesize method, waits for synthesis to complete, and returns an audio URL. Download the audio file from this URL.
# -*- coding: utf-8 -*-
import os
import dashscope
# The following configuration is for the China (Beijing) region. Replace "{WorkspaceId}" with your actual workspace ID. Regions differ in configuration.
client = dashscope.Client(
# If the API key is not configured as an environment variable, replace the next line with your API key: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="cn-beijing",
)
# Non-streaming call, returns an audio URL
result = client.audio.tts.http.synthesize(
"Today is a great day to build products that people love!",
model="cosyvoice-v3-plus", # When switching models, you must also switch to the corresponding voice for that version
voice="longanyang",
format="wav",
sample_rate=24000,
)
# Get the audio URL
print(f"Audio URL: {result.audio_url}")
print(f"Audio ID: {result.audio_id}")
if result.audio_id:
request_id = result.audio_id.removeprefix("audio_")
print(f"Request ID: {request_id}")
print(f"Expiration time: {result.expires_at}")
Streaming call
A streaming call uses the stream method, which returns an iterator that yields audio data chunk by chunk. This is suitable for real-time playback scenarios with low first-packet latency. In streaming mode, the final chunk (chunk.is_final is True) additionally returns the audio_url of the complete audio. When concatenating, write only chunks with non-empty chunk.audio to avoid duplicating audio content.
# -*- coding: utf-8 -*-
import os
import dashscope
# The following configuration is for the China (Beijing) region. Replace "{WorkspaceId}" with your actual workspace ID. Regions differ in configuration.
client = dashscope.Client(
# If the API key is not configured as an environment variable, replace the next line with your API key: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="cn-beijing",
)
# Streaming call, returns audio data chunk by chunk
stream_result = client.audio.tts.http.stream(
"Today is a great day to build products that people love!",
model="cosyvoice-v3-plus", # When switching models, you must also switch to the corresponding voice for that version
voice="longanyang",
format="wav",
sample_rate=24000,
)
# Iterate over the iterator, receiving audio data chunk by chunk
audio_chunks = []
for chunk in stream_result:
if chunk.audio: # Write only non-empty audio chunks to avoid duplicated audio
audio_chunks.append(chunk.audio)
print(f"Received audio data chunk, size: {len(chunk.audio)} bytes")
if chunk.sentence:
print(f"Sentence info: {chunk.sentence}")
if chunk.is_final: # Final chunk: carries the download URL of the complete audio and usage information
print(f"Audio ID: {chunk.audio_id}")
request_id = chunk.audio_id.removeprefix("audio_")
print(f"Request ID: {request_id}")
print(f"Audio URL: {chunk.audio_url}")
print(f"Usage: {chunk.usage}")
# Merge all audio data and save
full_audio = b"".join(audio_chunks)
print(f"Total audio size: {len(full_audio)} bytes")
with open("output.wav", "wb") as f:
f.write(full_audio)
print("Audio saved to output.wav")