CosyVoice については、CosyVoice Python SDK を参照してください。
前提条件
Qwen-Audio-TTS
エンドポイント
SDK のエンドポイントは、Client コンストラクターのパラメーター workspace/region によって決まります(下記のアドレスに対応し、WorkspaceId を含みます)。別のリージョンに切り替えるには、Client コンストラクターのパラメーターをそのリージョンの値に変更してください。
シンガポール
wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference
呼び出し時には、{WorkspaceId} を実際のワークスペース ID に置き換えてください。
中国(北京)
wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference
呼び出し時には、{WorkspaceId} を実際のワークスペース ID に置き換えてください。
dashscope CLI
dashscope コマンドラインから呼び出します。
export DASHSCOPE_API_KEY="your-api-key"
# 将 {WorkspaceId} 替换为业务空间ID,ap-southeast-1 替换为对应地域(美东: us-east-1, 德国: eu-central-1)
export DASHSCOPE_HTTP_BASE_URL="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
dashscope speech-synthesis create -m qwen-audio-3.0-tts-flash -t "你好世界" --voice longanhuan_v3.6
重要SDK Expert インタラクティブアシスタントは、自然言語を使って同じ開発タスクやトラブルシューティングを実行できます。詳細は
DashScope SDK Expert を参照してください。リージョンの完全な一覧については、Base URL の概要 を参照してください。
重要Alibaba Cloud Model Studio では、中国(北京)リージョンとシンガポールリージョン向けにワークスペース専用ドメインを提供開始しました。これらのドメインは、推論リクエストに対してより優れたパフォーマンスと高い安定性を発揮します。新しいドメインへの移行を推奨します:
- 中国(北京)リージョン:
dashscope.aliyuncs.comから{WorkspaceId}.cn-beijing.maas.aliyuncs.comへ移行 - シンガポールリージョン:
dashscope-intl.aliyuncs.comから{WorkspaceId}.ap-southeast-1.maas.aliyuncs.comへ移行
クイックスタート
この例ではシンガポールリージョンを使用します。コード内の {WorkspaceId} をお使いのワークスペース ID に置き換えてください。この例では、音声を現在のディレクトリに output.mp3 として保存します。
# coding=utf-8
import os
import dashscope
# If the environment variable is not configured, set your API key directly: api_key = "sk-xxx"
# The following is the configuration for the Singapore region. Replace "{WorkspaceId}" with your actual workspace ID. The region value varies by region.
client = dashscope.Client(
api_key=os.environ.get('DASHSCOPE_API_KEY'),
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
# Model
model = "qwen-audio-3.0-tts-flash"
# Voice
voice = "longanhuan_v3.6"
# Send the text to synthesize and get the binary audio
audio = client.audio.tts.synthesize("今天天气怎么样?", model=model, voice=voice)
# Save the audio to a local file
with open('output.mp3', 'wb') as f:
f.write(audio)
Qwen-Audio-TTS
SDK は音声合成のための主要なインターフェースを提供し、以下の呼び出し方法をサポートしています:
- 非ストリーミング呼び出し:ブロッキング方式。テキスト全体を一度に送信し、完全な音声をそのまま返します。短いテキストの音声合成シナリオに適しています。
- 単方向ストリーミング呼び出し:ノンブロッキング方式。テキスト全体を一度に送信し、
streamが返す音声チャンクを反復処理することでデータを受信します。高いリアルタイム性が求められる短いテキストの音声合成シナリオに適しています。 - 双方向ストリーミング呼び出し:ノンブロッキング方式。テキストの断片を複数回に分けて送信でき、セッションの
audio_chunks()/events()を反復処理することで、インクリメンタルに合成される音声ストリームをリアルタイムで受信します。高いリアルタイム性が求められる長いテキストの音声合成シナリオに適しています。
非ストリーミング呼び出し
1 回の呼び出しで送信するテキストは 20,000 文字を超えてはなりません。超過した場合、エラーが返されます。
重要synthesize や stream の各呼び出しはそれぞれ独自のセッションを作成するため、インスタンスを再利用する必要はありません。
# coding=utf-8
import os
import dashscope
# The API Key of the Singapore region is different from that of the Beijing region. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If the environment variable is not configured, set your API key directly: api_key = "sk-xxx"
# The following is the configuration for the Singapore region. Replace "{WorkspaceId}" with your actual workspace ID. The region value varies by region.
client = dashscope.Client(
api_key=os.environ.get('DASHSCOPE_API_KEY'),
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
# Model
model = "qwen-audio-3.0-tts-flash"
# Voice
voice = "longanhuan_v3.6"
# Send the text to synthesize and get the binary audio
audio = client.audio.tts.synthesize("今天天气怎么样?", model=model, voice=voice)
# Save the audio to a local file
with open('output.mp3', 'wb') as f:
f.write(audio)
単方向ストリーミング呼び出し
1 回の呼び出しで送信するテキストは 20,000 文字を超えてはなりません。超過した場合、エラーが返されます。
重要synthesize や stream の各呼び出しはそれぞれ独自のセッションを作成するため、インスタンスを再利用する必要はありません。
# coding=utf-8
import os
from datetime import datetime
import dashscope
def get_timestamp():
now = datetime.now()
formatted_timestamp = now.strftime("[%Y-%m-%d %H:%M:%S.%f]")
return formatted_timestamp
# The API Key of the Singapore region is different from that of the Beijing region. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If the environment variable is not configured, set your API key directly: api_key = "sk-xxx"
# The following is the configuration for the Singapore region. Replace "{WorkspaceId}" with your actual workspace ID. The region value varies by region.
client = dashscope.Client(
api_key=os.environ.get('DASHSCOPE_API_KEY'),
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
# Model
model = "qwen-audio-3.0-tts-flash"
# Voice
voice = "longanhuan_v3.6"
# Send the complete text at once, and receive the binary audio chunk by chunk
with open("output.mp3", "wb") as f:
for chunk in client.audio.tts.stream("今天天气怎么样?", model=model, voice=voice):
print(get_timestamp() + " 二进制音频长度为:" + str(len(chunk)))
f.write(chunk)
print("语音合成完成,所有合成结果已被接收:" + get_timestamp())
双方向ストリーミング呼び出し
1 回のリクエストで送信するテキストは 20,000 文字を超えてはならず、送信したテキストの累積合計長は 200,000 文字を超えてはなりません。
-
ストリーミング入力モードでは、セッションの
send_textを複数回呼び出して、テキスト断片を順番に送信できます。サーバーは受信したテキスト断片を自動的に文単位に分割します。- 完全な文は即時に合成されます
- 不完全な文はキャッシュされ、完全な文になった後に合成されます
stopが呼び出されると、サーバーは受信済みで未処理のテキスト断片(不完全な文を含む)をすべて強制的に合成します。 -
テキスト断片の送信間隔は 23 秒を超えてはなりません。超過した場合、"23 秒後のリクエストタイムアウト" エラーが発生します。
送信するテキストがなくなったら、直ちに
stopを呼び出してタスクを終了してください。重要必ず
stopメソッドを呼び出してください。呼び出さない場合、末尾のテキストが音声に変換されないことがあります。サーバー側で 23 秒の強制タイムアウト機構が適用されており、クライアント側で変更することはできません。
# coding=utf-8
#
# pyaudio installation notes:
# On macOS, run the following commands:
# brew install portaudio
# pip install pyaudio
# On Debian/Ubuntu, run the following commands:
# sudo apt-get install python-pyaudio python3-pyaudio
# or
# pip install pyaudio
# On CentOS, run the following commands:
# sudo yum install -y portaudio portaudio-devel && pip install pyaudio
# On Microsoft Windows, run the following command:
# python -m pip install pyaudio
import os
import time
import pyaudio
from concurrent.futures import ThreadPoolExecutor
import dashscope
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 Key of the Singapore region is different from that of the Beijing region. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If the environment variable is not configured, set your API key directly: api_key = "sk-xxx"
# The following is the configuration for the Singapore region. Replace "{WorkspaceId}" with your actual workspace ID. The region value varies by region.
client = dashscope.Client(
api_key=os.environ.get('DASHSCOPE_API_KEY'),
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
# Model
model = "qwen-audio-3.0-tts-flash"
# Voice
voice = "longanhuan_v3.6"
test_text = [
"流式文本语音合成SDK,",
"可以将输入的文本",
"合成为语音二进制数据,",
"相比于非流式语音合成,",
"流式合成的优势在于实时性",
"更强。用户在输入文本的同时",
"可以听到接近同步的语音输出,",
"极大地提升了交互体验,",
"减少了用户等待时间。",
"适用于调用大规模",
"语言模型(LLM),以",
"流式输入文本的方式",
"进行语音合成的场景。",
]
# Create a bidirectional streaming synthesis session: the connection is established automatically when entering the with context
with client.audio.tts.connect(
model=model,
voice=voice,
format="pcm",
sample_rate=22050,
) as session:
# Initialize the player
player = pyaudio.PyAudio()
stream = player.open(format=pyaudio.paInt16, channels=1, rate=22050, output=True)
# Receiving thread: iterate over the audio data and play it in real time
def receive_audio():
for chunk in session.audio_chunks():
print(get_timestamp() + " 二进制音频长度为:" + str(len(chunk)))
stream.write(chunk)
with ThreadPoolExecutor(max_workers=1) as pool:
receiver = pool.submit(receive_audio)
# Send the text to synthesize in a streaming manner
for text in test_text:
session.send_text(text)
time.sleep(0.1)
# End the streaming synthesis
session.stop()
receiver.result()
print("语音合成完成,所有合成结果已被接收:" + get_timestamp())
# Stop the player
stream.stop_stream()
stream.close()
player.terminate()
# The first WebSocket connection is established when the first text is sent, so the first package delay includes the connection establishment time
print('[Metric] 首包延迟为:{}毫秒'.format(session.first_package_delay))
リクエストパラメータ
Qwen-Audio-TTS
以下のパラメータは client.audio.tts の synthesize/stream/connect メソッドで設定され、合成音声のモデル、ボイス、フォーマット、音響特性を制御します(model、voice、format、sample_rate、volume、rate、pitch、language_hints、enable_ssml は名前付きパラメータであり、残りのパラメータは parameters ディクショナリで渡します)。
| パラメータ | 型 | 必須 | 説明 |
|---|---|---|---|
model | str | はい | モデル名。 |
voice | str | はい | 音声合成に使用するボイス。
|
format | str | いいえ | 音声のエンコード形式。 デフォルト値: mp3。 対応フォーマットは mp3、wav、pcm です。サンプルレートは |
volume | int | いいえ | 音量。 デフォルト値:50。 値の範囲:[0, 100]。 |
rate | float | いいえ | 話速。 デフォルト値:1.0。 値の範囲:[0.5, 2.0]。 |
pitch | float | いいえ | ピッチ(音の高さ)。 デフォルト値:1.0。 値の範囲:[0.5, 2.0]。 |
bit_rate | int | いいえ | 音声のビットレート(kbps)。音声フォーマットが mp3 または opus の場合、bit_rate パラメータでビットレートを調整できます。デフォルト値:32。 値の範囲:[6, 510]。
|
word_timestamp_enabled | bool | いいえ | 文字単位のタイムスタンプを有効にするかどうか。 デフォルト値:false。 ストリーミング出力モードでのみ利用できます。音声クローンに対応しています。対応するシステム音声については、Qwen-Audio-TTS の音声リストを参照してください。
|
seed | int | いいえ | 生成に使用される乱数シード。合成結果に変化が生じます。モデルのバージョン、テキスト、音声などのパラメータがすべて同じ場合、同じシードを使用すると同じ合成結果を再現できます。 デフォルト値:0。 値の範囲:[0, 65535]。 |
language_hints | list[str] | いいえ | 注記qwen-audio-3.1-tts-flash の多言語・方言音声を使用する場合、このパラメータで言語または方言を指定できます。詳細な使い方については、多言語・方言音声の設定方法を参照してください。 音声合成の合成品質を向上させるため、合成の対象言語を指定します。 数字や略語、記号の読み上げ方、または低リソース言語の合成品質が期待に合わない場合に使用してください。例:
値の範囲
注記
|
instruction | str | いいえ | 方言、感情、ロールなどの合成効果を制御するために使用するインストラクションを設定します。 使用方法については、インストラクション制御を参照してください。 |
enable_aigc_tag | bool | いいえ | 生成された音声に不可視のAIGCラベルを追加するかどうか。true に設定すると、対応形式(wav/mp3/opus)の音声に不可視ラベルが埋め込まれます。 デフォルト値:false。
|
aigc_propagator | str | いいえ | 不可視AIGCラベル内の ContentPropagator フィールドを設定します。このフィールドはコンテンツの伝播者を識別します。enable_aigc_tag が true の場合にのみ有効になります。デフォルト値:Alibaba Cloud UID。
|
aigc_propagate_id | str | いいえ | 不可視AIGCラベル内の PropagateID フィールドを設定します。このフィールドは特定の伝播アクションを一意に識別します。enable_aigc_tag が true の場合にのみ有効になります。デフォルト値:本音声合成リクエストの Request ID。
|
hot_fix | dict | いいえ | テキストホットフィックス設定。指定した単語の発音をカスタマイズしたり、合成対象のテキストを置き換えたりするために使用します。 パラメーターの説明:
例: |
|
| いいえ | Markdownフィルタリングを有効にするかどうか。有効にすると、サービスは合成前にMarkdownを音声に適したテキストに変換します。 デフォルト値:
|
API リファレンス
コアリソース (client.audio.tts)
リソースパス: client.audio.tts
機能: WebSocket ベースの音声合成であり、一括合成 (synthesize)、ストリーミング合成 (stream)、双方向ストリーミングセッション (connect) の 3 つの呼び出しモードを提供します。
stream() - ストリーミング呼び出し
方法签名:
def stream(self, text: str, *, model: str, voice: str,
format: str = "mp3", sample_rate: int = 22050, ...) -> Iterator[bytes]
参数说明:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
text | str | 是 | 待合成的完整文本,长度不得超过20000字符。 |
返回值:Iterator[bytes],逐块产出的音频数据。
説明: テキスト全体を一度に送信し、音声をチャンク単位で順次返す (Iterator[bytes]) ストリーミング合成です。リアルタイム性が重視される短いテキストの音声合成シナリオに適しています。テキストを分割して送信するには、双方向ストリーミングセッション (connect) を使用してください。
send_text() - ストリーミング入力 (セッションメソッド)
双向流式会话(client.audio.tts.connect(...))中分片提交文本。
方法签名:
def send_text(self, text: str) -> None
参数说明:text为当前待合成的文本片段。可多次调用send_text以追加文本,单次不超过20000字符,累计不超过20万字符。发送文本与接收音频需并发进行(配合audio_chunks()/events()和stop使用)。
stop() - ストリーミング入力の終了 (セッションメソッド)
方法签名:
def stop(self) -> None
说明:通知服务端所有文本已发送完毕。调用后不阻塞当前线程,接收线程需继续消费audio_chunks()/events()直到剩余文本合成完成并返回所有音频数据。未调用此方法可能导致尾部文本无法转换为语音。
セッションのメトリクスと応答 (セッション属性)
session.first_package_delay
session.usage
session.last_response
first_package_delay:float,从发送文本到收到第一块音频数据的延迟时间(毫秒)。需在合成完成后读取。usage:dict,最近一次合成任务的用量信息。last_response:dict,最近一次合成任务的响应消息(含header/payload键)。最近一次请求的request_id可从session.last_response的header中获取,可用于问题排查和日志关联。
audio_chunks() - 音声データのイテレーション
方法签名:
def audio_chunks(self) -> Iterator[bytes]
返回值:Iterator[bytes],逐块产出的音频二进制数据片段,格式由format参数指定。
说明:在接收线程中迭代,逐块接收音频数据,合成过程中会产出多块。可将数据写入文件或送入播放设备。同一会话只允许一个events()或audio_chunks()读取者。
events() - サーバー側イベントのイテレーション
方法签名:
def events(self) -> Generator[Union[Dict, bytes], None, None]
戻り値: サーバー側の応答イベント (dict、リクエスト情報を含む header と出力情報を含む payload) と音声 bytes の両方を生成します。そのうち payload.output にはイベントタイプや元テキストなどの情報が含まれます。詳細については、以下を参照events() イベントの output フィールド。
説明: 受信スレッドでサーバー側の応答をイテレーションします。応答には合成イベントの出力情報 (イベントタイプ、元テキスト、文情報など) が含まれます。詳細は payload.output に直接アクセスして確認できます。
エラー処理
合成过程中发生错误时,ws层会以DashScopeError异常抛出,异常触发后连接将自动关闭。可在发送/接收处使用try/except捕获并记录错误日志以便排查问题:
from dashscope import DashScopeError
try:
...
except DashScopeError as e:
print(e.code, e.message, e.request_id)
セッションのライフサイクル
withコンテキストに入ると接続が自動的に確立されます (事前に音声出力ストリームを初期化したり、ファイルリソースを開いておくことができます)。- すべてのテキストの合成が完了し、すべての音声データが生成されると、
events()/audio_chunks()のイテレーションが終了します。その後、first_package_delayなどのパフォーマンスメトリクスを読み取ることができます。 withコンテキストを抜けると接続が自動的に閉じられます (その後で音声再生デバイスなどのリソースを解放できます)。
events() イベントの output フィールド
会话events()迭代产出的事件dict中,payload.output包含合成事件的输出信息,可用于跟踪合成进度和获取逐句信息。以下为output字段的结构说明:
| 字段 | 类型 | 说明 |
|---|---|---|
type | str | 事件类型。取值为sentence-begin(句子合成开始)、sentence-synthesis(句子合成中)或sentence-end(句子合成结束)。 |
original_text | str | 当前句子的原始文本。在sentence-begin和sentence-end事件中返回。 |
sentence | dict | 句子信息。包含index(句子序号)和words(词列表,开启word_timestamp_enabled时返回时间戳信息)。 |
消息示例:
{
"header": {
"task_id": "xxx",
"event": "result-generated",
"attributes": {}
},
"payload": {
"output": {
"type": "sentence-begin",
"original_text": "今天天气怎么样?",
"sentence": {
"index": 0,
"words": []
}
}
}
}
解析示例:
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}, 原始文本: {original_text}')
Qwen-Audio-TTS
共通の説明
- コアリソース (
client.audio.tts) - stream() - ストリーミング呼び出し
- send_text() - ストリーミング入力 (セッションメソッド)
- stop() - ストリーミング入力の終了 (セッションメソッド)
- セッションのメトリクスと応答 (セッション属性)
- audio_chunks() - 音声データのイテレーション
- events() - サーバー側イベントのイテレーション
- エラー処理
- セッションのライフサイクル
- events() イベントの output フィールド
呼び出しエントリ
# One-shot synthesis: returns the complete audio bytes
audio = client.audio.tts.synthesize(
text, # text is required (positional argument)
model="qwen-audio-3.0-tts-flash", # The model that the voice belongs to
voice="longanhuan_v3.6", # The voice
format="mp3", # Audio encoding format, default "mp3"
sample_rate=22050, # Sample rate, default 22050
)
# Streaming synthesis: yields audio bytes chunk by chunk (write/play while receiving)
for chunk in client.audio.tts.stream(text, model=..., voice=...):
...
# Bidirectional streaming session: send text in segments; the connection is established automatically when entering the with context
with client.audio.tts.connect(model=..., voice=...) as session:
session.send_text(text) # 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() - 非ストリーミング呼び出し
メソッドシグネチャ:
def synthesize(self, text: str, *, model: str,
voice: str, 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
パラメータ説明:
| パラメータ | 型 | 必須 | 説明 |
|---|---|---|---|
text | str | はい | 合成するテキスト全文。長さは20,000文字を超えないようにしてください。 |
戻り値:bytes、完全な音声データ。
説明:ブロッキングして完全な音声データを一度に返す非ストリーミング呼び出しです。短いテキストや、厳密なリアルタイム性が求められないシナリオに適しています。synthesizeとstreamは呼び出しごとに新しいセッションを作成するため、インスタンスを再利用する必要はありません。
cancel() - ストリーミング合成のキャンセル(セッションメソッド)
メソッドシグネチャ:
def cancel(self) -> None
説明:現在のラウンドのストリーミング音声合成タスクをキャンセルします。この呼び出しの後、SDKは直ちに現在のタスクを終了します。キャンセル後は現在のセッションでテキストを送信できなくなります。合成を続行する必要がある場合は、新しいセッションを作成してください。
セッションとイベントの反復処理
ストリーミング合成ではコールバックインターフェースを使用しなくなりました。音声およびサーバー側のイベントは、セッションの反復処理メソッドを通じて受け取ります。stream()/synthesize()ではセッション管理は不要です。双方向ストリーミングセッション(client.audio.tts.connect(...))のライフサイクルは次のとおりです:withコンテキストに入ると自動的に接続が確立される → 複数回のsend_text()呼び出し → stop() → すべての結果を読み取る → コンテキストを抜けると自動的に接続が閉じられる。