このトピックでは、 DashScope Python SDK を使用してリアルタイム音声合成 (Qwen) を呼び出す際の、主要なインターフェースとリクエストパラメーターを説明します。
ユーザーガイド:モデルの紹介と選択の推奨事項については、「リアルタイム音声合成 – Qwen」または「音声合成 – Qwen」をご参照ください。
前提条件
DashScope Python SDK 1.25.11 以降が必要です。
開始方法
サーバーコミットモード
import os
import base64
import threading
import time
import dashscope
from dashscope.audio.qwen_tts_realtime import *
qwen_tts_realtime: QwenTtsRealtime = None
text_to_synthesize = [
'Right? I love supermarkets like this.',
'Especially during Chinese New Year,',
'I go shopping at supermarkets.',
'And I feel',
'absolutely thrilled!',
'I want to buy so many things!'
]
DO_VIDEO_TEST = False
def init_dashscope_api_key():
"""
DashScope API キーを設定します。詳細:
https://github.com/aliyun/alibabacloud-bailian-speech-demo/blob/master/PREREQUISITES.md
"""
# API キーは Singapore リージョンと Beijing リージョンで異なります。API キーの取得: https://www.alibabacloud.com/help/model-studio/get-api-key
if 'DASHSCOPE_API_KEY' in os.environ:
dashscope.api_key = os.environ[
'DASHSCOPE_API_KEY'] # 環境変数 DASHSCOPE_API_KEY から API キーを読み込みます
else:
dashscope.api_key = 'your-dashscope-api-key' # API キーを手動で設定します
class MyCallback(QwenTtsRealtimeCallback):
def __init__(self):
self.complete_event = threading.Event()
self.file = open('result_24k.pcm', 'wb')
def on_open(self) -> None:
print('connection opened, init player')
def on_close(self, close_status_code, close_msg) -> None:
self.file.close()
print('connection closed with code: {}, msg: {}, destroy player'.format(close_status_code, close_msg))
def on_event(self, response: str) -> None:
try:
global qwen_tts_realtime
type = response['type']
if 'session.created' == type:
print('start session: {}'.format(response['session']['id']))
if 'response.audio.delta' == type:
recv_audio_b64 = response['delta']
self.file.write(base64.b64decode(recv_audio_b64))
if 'response.done' == type:
print(f'response {qwen_tts_realtime.get_last_response_id()} done')
if 'session.finished' == type:
print('session finished')
self.complete_event.set()
except Exception as e:
print('[Error] {}'.format(e))
return
def wait_for_finished(self):
self.complete_event.wait()
if __name__ == '__main__':
init_dashscope_api_key()
print('Initializing ...')
callback = MyCallback()
qwen_tts_realtime = QwenTtsRealtime(
# 指示コントロールを使用するには、モデルを qwen3-tts-instruct-flash-realtime に置き換えます
model='qwen3-tts-flash-realtime',
callback=callback,
# Singapore リージョン
url='wss://dashscope-intl.aliyuncs.com/api-ws/v1/realtime'
)
qwen_tts_realtime.connect()
qwen_tts_realtime.update_session(
voice = 'Cherry',
response_format = AudioFormat.PCM_24000HZ_MONO_16BIT,
# 指示コントロールを使用するには、次の行のコメントを解除し、モデルを qwen3-tts-instruct-flash-realtime に置き換えます
# instructions='Speak quickly with a rising intonation, suitable for introducing fashion products.',
# optimize_instructions=True,
mode = 'server_commit'
)
for text_chunk in text_to_synthesize:
print(f'send text: {text_chunk}')
qwen_tts_realtime.append_text(text_chunk)
time.sleep(0.1)
qwen_tts_realtime.finish()
callback.wait_for_finished()
print('[Metric] session: {}, first audio delay: {}'.format(
qwen_tts_realtime.get_session_id(),
qwen_tts_realtime.get_first_audio_delay(),
))
コミットモード
import base64
import os
import threading
import dashscope
from dashscope.audio.qwen_tts_realtime import *
qwen_tts_realtime: QwenTtsRealtime = None
text_to_synthesize = [
'This is the first sentence.',
'This is the second sentence.',
'This is the third sentence.',
]
DO_VIDEO_TEST = False
def init_dashscope_api_key():
"""
DashScope API キーを設定します。詳細:
https://github.com/aliyun/alibabacloud-bailian-speech-demo/blob/master/PREREQUISITES.md
"""
# API キーは Singapore リージョンと Beijing リージョンで異なります。API キーの取得: https://www.alibabacloud.com/help/model-studio/get-api-key
if 'DASHSCOPE_API_KEY' in os.environ:
dashscope.api_key = os.environ[
'DASHSCOPE_API_KEY'] # 環境変数 DASHSCOPE_API_KEY から API キーを読み込みます
else:
dashscope.api_key = 'your-dashscope-api-key' # API キーを手動で設定します
class MyCallback(QwenTtsRealtimeCallback):
def __init__(self):
super().__init__()
self.response_counter = 0
self.complete_event = threading.Event()
self.file = open(f'result_{self.response_counter}_24k.pcm', 'wb')
def reset_event(self):
self.response_counter += 1
self.file = open(f'result_{self.response_counter}_24k.pcm', 'wb')
self.complete_event = threading.Event()
def on_open(self) -> None:
print('connection opened, init player')
def on_close(self, close_status_code, close_msg) -> None:
print('connection closed with code: {}, msg: {}, destroy player'.format(close_status_code, close_msg))
def on_event(self, response: str) -> None:
try:
global qwen_tts_realtime
type = response['type']
if 'session.created' == type:
print('start session: {}'.format(response['session']['id']))
if 'response.audio.delta' == type:
recv_audio_b64 = response['delta']
self.file.write(base64.b64decode(recv_audio_b64))
if 'response.done' == type:
print(f'response {qwen_tts_realtime.get_last_response_id()} done')
self.complete_event.set()
self.file.close()
if 'session.finished' == type:
print('session finished')
self.complete_event.set()
except Exception as e:
print('[Error] {}'.format(e))
return
def wait_for_response_done(self):
self.complete_event.wait()
if __name__ == '__main__':
init_dashscope_api_key()
print('Initializing ...')
callback = MyCallback()
qwen_tts_realtime = QwenTtsRealtime(
# 指示コントロールを使用するには、モデルを qwen3-tts-instruct-flash-realtime に置き換えます
model='qwen3-tts-flash-realtime',
callback=callback,
# Singapore リージョン
url='wss://dashscope-intl.aliyuncs.com/api-ws/v1/realtime'
)
qwen_tts_realtime.connect()
qwen_tts_realtime.update_session(
voice = 'Cherry',
response_format = AudioFormat.PCM_24000HZ_MONO_16BIT,
# 指示コントロールを使用するには、次の行のコメントを解除し、モデルを qwen3-tts-instruct-flash-realtime に置き換えます
# instructions='Speak quickly with a rising intonation, suitable for introducing fashion products.',
# optimize_instructions=True,
mode = 'commit'
)
print(f'send text: {text_to_synthesize[0]}')
qwen_tts_realtime.append_text(text_to_synthesize[0])
qwen_tts_realtime.commit()
callback.wait_for_response_done()
callback.reset_event()
print(f'send text: {text_to_synthesize[1]}')
qwen_tts_realtime.append_text(text_to_synthesize[1])
qwen_tts_realtime.commit()
callback.wait_for_response_done()
callback.reset_event()
print(f'send text: {text_to_synthesize[2]}')
qwen_tts_realtime.append_text(text_to_synthesize[2])
qwen_tts_realtime.commit()
callback.wait_for_response_done()
qwen_tts_realtime.finish()
print('[Metric] session: {}, first audio delay: {}'.format(
qwen_tts_realtime.get_session_id(),
qwen_tts_realtime.get_first_audio_delay(),
))
詳細については、GitHub にアクセスして、追加のサンプルコードをダウンロードしてください。
リクエストパラメータ
QwenTtsRealtime コンストラクターでは、以下のパラメーターを設定します。
|
パラメーター |
タイプ |
必須 |
説明 |
|
model |
str |
はい |
モデル名 (「サポートされているモデル」をご参照ください)。 |
|
url |
str |
はい |
China (Beijing): Singapore: |
update_session を使用して、以下のパラメーターを設定します。
|
パラメーター |
タイプ |
必須 |
説明 |
|
voice |
str |
はい |
音声合成に使用する音声です。詳細については、「サポートされる音声」をご参照ください。 システム音声とカスタム音声がサポートされています。
|
|
language_type |
str |
いいえ |
合成オーディオの言語です。デフォルト値は
|
|
mode |
str |
いいえ |
インタラクションパターンです。有効な値は以下のとおりです。
|
|
format |
str |
いいえ |
モデルからのオーディオ出力フォーマットです。 サポートされるフォーマット:
Qwen-TTS-Realtime (「サポートされるモデル」をご参照ください) は |
|
sample_rate |
int |
いいえ |
モデルからのオーディオ出力のサンプルレート (Hz) です。 サポートされるサンプルレート:
Qwen-TTS-Realtime (「サポートされるモデル」をご参照ください) は 24000 のみをサポートします。 |
|
speech_rate |
float |
いいえ |
オーディオの話速です。1.0 が通常速度です。1.0 未満は低速、1.0 より大きい値は高速になります。 デフォルト値:1.0 有効範囲:[0.5, 2.0] Qwen-TTS-Realtime (「サポートされるモデル」をご参照ください) はこのパラメーターをサポートしません。 |
|
volume |
int |
いいえ |
オーディオのボリュームです。 デフォルト値:50 有効範囲:[0, 100] Qwen-TTS-Realtime (「サポートされるモデル」をご参照ください) はこのパラメーターをサポートしません。 |
|
pitch_rate |
float |
いいえ |
合成オーディオのピッチです。 デフォルト値:1.0 有効範囲:[0.5, 2.0] Qwen-TTS-Realtime (「サポートされるモデル」をご参照ください) はこのパラメーターをサポートしません。 |
|
bit_rate |
int |
いいえ |
ビットレート (kbps) です。ビットレートが高いほどオーディオ品質が向上し、ファイルサイズも大きくなります。このパラメーターは、オーディオフォーマット ( デフォルト値:128 有効範囲:[6, 510] Qwen-TTS-Realtime (「サポートされるモデル」をご参照ください) はこのパラメーターをサポートしません。 |
|
instructions |
str |
いいえ |
命令を設定します。「リアルタイム音声合成 - Qwen」をご参照ください。 デフォルト値:なし。設定されていない場合、このパラメーターは効果を持ちません。 長さ制限:長さは 1600 トークンを超えてはなりません。 サポート言語:中国語と英語のみサポートされます。 適用範囲:この機能は Qwen3-TTS-Instruct-Flash-Realtime モデルシリーズでのみ利用可能です。 |
|
optimize_instructions |
bool |
いいえ |
デフォルト値: False 動作: True に設定すると、システムは 適用シナリオ:高品質かつ詳細な音声表現が求められるシナリオでこの機能を有効にしてください。 依存関係:このパラメーターは 適用範囲:この機能は Qwen3-TTS-Instruct-Flash-Realtime モデルシリーズでのみ利用可能です。 |
主要なインターフェイス
QwenTtsRealtime クラス
インポート: from dashscope.audio.qwen_tts_realtime import QwenTtsRealtime
|
メソッドシグネチャ |
サーバー応答イベント (コールバック経由で配信) |
説明 |
|
Session created Session configuration updated |
サーバーに接続します。 |
|
Session configuration updated |
デフォルトのセッション構成を更新します。パラメーターの詳細については、「Request parameters」をご参照ください。 接続後、サーバーはデフォルトの入力構成と出力構成を返します。接続直後にこのメソッドを呼び出し、これらのデフォルト設定を更新します。 サーバーは session.update イベントを受信した時点でパラメーターを検証します。検証に失敗した場合はエラーを返し、成功した場合はセッション構成を更新します。 |
|
None |
テキストチャンクをクラウド入力バッファー (コミット前のテキストを一時的に格納する領域) に追加します。
|
|
Clear text received by the server |
クラウドバッファー内のテキストをすべてクリアします。 |
|
Submit text and trigger speech synthesis New output content added New content added to assistant message Incremental audio generated by the model Audio generation completed Streaming of audio content for assistant message completed Streaming of entire output item for assistant message completed Synthesis response completed |
クラウドバッファー内のテキストをすべてコミットし、直ちに音声合成します。バッファーが空の場合はエラーを返します。
|
|
Session completed |
タスクを終了します。 |
|
None |
接続を閉じます。 |
|
None |
現在のタスクのセッション ID を取得します。 |
|
None |
直近の応答の応答 ID を取得します。 |
|
None |
最初のオーディオパケットが到着するまでの遅延を取得します。 |
コールバックインターフェイス (QwenTtsRealtimeCallback)
サーバーは、コールバックを通じて応答とデータを送信します。これらを処理するには、コールバックメソッドを実装します。
インポート: from dashscope.audio.qwen_tts_realtime import QwenTtsRealtimeCallback
|
メソッド |
パラメーター |
戻り値 |
説明 |
|
None |
None |
サーバーへの接続が確立されたときに呼び出されます。 |
|
message:サーバー応答イベント。 |
None |
API 呼び出しの応答、モデルが生成したテキスト、オーディオが含まれます。詳細については、「Server events」をご参照ください。 |
|
close_status_code:WebSocket のクローズステータスコード。 close_msg:WebSocket のクローズメッセージ。 |
None |
サーバーが接続を閉じた後に呼び出されます。 |