本文档介绍如何使用 DashScope Python SDK 调用实时音视频翻译(Qwen-LiveTranslate-Realtime)模型。
连接与鉴权参见 WebSocket 接入;事件字段与 JSON 示例参见客户端事件和服务端事件。
前提条件
- 安装SDK,确保DashScope SDK版本不低于2.0.1。
- 获取与配置 API Key。
重要阿里云百炼为华北2(北京)、新加坡地域推出了业务空间专属域名,能够为推理请求提供卓越的性能和更高的稳定性,建议迁移至新域名:
- 华北2(北京)地域:从
wss://dashscope.aliyuncs.com迁移至wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com - 新加坡地域:从
wss://dashscope-intl.aliyuncs.com迁移至wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
其中 {WorkspaceId} 为您的业务空间 ID,可在阿里云百炼控制台的业务空间详情页面查看。现有域名仍可正常使用。
请求参数
-
以下参数通过
client.audio.realtime的connect方法设置。服务端事件不再通过回调接收:在接收线程中迭代会话的events()处理(见事件迭代(events()))。点击查看示例代码
import os import dashscope # The following is the configuration for the China (Beijing) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. Configurations differ by region. client = dashscope.Client( # If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: api_key="sk-xxx" api_key=os.getenv("DASHSCOPE_API_KEY"), workspace="{WorkspaceId}", region="cn-beijing", ) # Create a real-time translation session: entering the with context automatically establishes the connection with client.audio.realtime.connect( model='qwen3.5-livetranslate-flash-realtime', ) as session: # Receiving thread: iterate over the server events for event in session.events(): event_type = event.get('type', '') if event_type == 'session.created': print(f"Session created: {event['session']['id']}") elif event_type == 'response.audio_transcript.done': print(f"Translation result: {event['transcript']}") elif event_type == 'response.audio.delta': # Process the incremental audio data (base64) audio_b64 = event.get('delta', '') # The audio data can be decoded and then played or saved elif event_type == 'response.done': print('======Response Done======') elif event_type == 'input_audio_buffer.speech_started': print('======Speech Start======') elif event_type == 'input_audio_buffer.speech_stopped': print('======Speech Stop======')参数 类型 是否必须 说明 modelstr是
指定要使用的模型名称,推荐使用
qwen3.5-livetranslate-flash-realtime。ws_urlstr否
会话端点。缺省时由Client构造参数
workspace/region自动推导实时翻译服务地址(华北2(北京):wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/realtime;新加坡:wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime)。调用时请将
{WorkspaceId}替换为真实的业务空间ID。 -
以下参数通过会话的
update_session方法设置。点击查看示例代码
# Set the translation parameters translation_params = { 'language': 'en', # Target language 'corpus': { 'phrases': { '人工智能': 'Artificial Intelligence', '机器学习': 'Machine Learning' } } } # Update the session configuration session.update_session( output_modalities=['text', 'audio'], voice='Tina', translation_params=translation_params, )参数
类型
是否必须
说明
output_modalitiesList[str]否
模型输出模态。
默认值:
["text", "audio"]。取值范围:
["text"]:仅输出文本["text", "audio"]:输出文本和音频
voicestr是
生成音频的音色。
默认值:
Qwen3.5-LiveTranslate-Flash-Realtime默认音色为:
Tina
可选值:参见支持的音色。
input_audio_transcription_modelstr否
将
input_audio_transcription_model设为qwen3-asr-flash-realtime,服务端将返回源语言语音识别结果。translation_paramsDict否
翻译相关配置。
enable_turn_detectionbool否
是否启用 VAD(语音活动检测)。
默认值:
True,即启用 VAD 模式,服务端自动检测语音起止并自动触发翻译。 -
以下参数通过
update_session方法的translation_params字典设置。点击查看示例代码
translation_params = { 'language': 'en', # Target language code 'corpus': { 'phrases': { '人工智能': 'Artificial Intelligence', # Source-language term: target-language translation '机器学习': 'Machine Learning' } } }参数
类型
是否必须
说明
languagestr否
翻译目标语言代码。
默认值:
en。可选值:参见支持的语种。
corpusdict否
热词配置,用于提升特定词汇的翻译准确性。
corpus.phrasesdict否
热词映射表。key 为源语言词汇,value 为目标语言对应翻译。
示例:
{'人工智能': 'Artificial Intelligence'}
关键接口
会话(RealtimeSession)
实时翻译会话通过client.audio.realtime.connect(model=...)创建,进入with上下文时自动建立连接(也可调用会话的connect()方法手动建立)。
| 方法签名 | 服务端响应事件(通过events()迭代下发) | 说明 |
|---|---|---|
|
| 和服务端创建连接。进入 |
|
| 用于更新会话配置,建议在连接建立后首先调用该方法进行设置。若未调用该方法,系统将使用默认配置。只需关注会话 |
|
| 通知服务端结束会话,服务端收到会话结束通知后将完成最后的语音翻译。 |
| 无 | 将音频数据片段追加到云端输入音频缓冲区,支持Base64字符串或原始 |
|
| Manual 模式下,提交之前通过 |
|
| 清空当前云端缓冲区中尚未提交的音频数据。 |
| 无 | 终止任务,并关闭连接。退出 |
| 无 | 获取当前任务的session_id(从 |
| 无 | 获取最近一次response的response_id(从 |
事件迭代(events())
服务端会通过事件的方式,将服务端响应事件和数据返回给客户端。在接收线程中迭代会话的events()处理服务端事件,session.finished事件后迭代结束。
error事件会以DashScopeError异常抛出,可在接收线程中使用try/except捕获。
捕获异常后如何继续接收事件
捕获 DashScopeError 后,原来的 events() 迭代已经结束。仅在外层使用 try/except 捕获异常,不会让它自动继续接收事件。
如果 WebSocket 连接仍可用,修正请求后重新调用 events(),或用 recv_event() 逐条接收。连接已关闭时,先重新建连并配置会话,再开始接收。
排查错误原因时,可从异常的 body 读取服务端返回的原始错误事件。
| 方法签名 | 参数 | 说明 |
|---|---|---|
| event:服务端事件 | 迭代接收服务端事件( |
| event:服务端事件 | 读取一条服务端事件,正常关闭后返回 |
完整示例
以下示例展示如何从麦克风实时录音并进行翻译。
麦克风实时翻译示例代码
import os
import sys
import base64
import signal
import pyaudio
from concurrent.futures import ThreadPoolExecutor
import dashscope
from dashscope.v2 import DashScopeError
def main():
# Check the API Key
if not os.environ.get("DASHSCOPE_API_KEY"):
print("请设置环境变量 DASHSCOPE_API_KEY")
sys.exit(1)
# The following is the configuration for the Singapore (ap-southeast-1) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. Configurations differ by region.
client = dashscope.Client(
# If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API Key: api_key="sk-xxx"
api_key=os.environ["DASHSCOPE_API_KEY"],
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
# Initialize PyAudio
pya = pyaudio.PyAudio()
# Initialize the speaker (for playing the translated speech)
speaker = pya.open(
format=pyaudio.paInt16,
channels=1,
rate=24000,
output=True,
frames_per_buffer=2400
)
# Initialize the microphone (for capturing the speech input)
mic = pya.open(
format=pyaudio.paInt16,
channels=1,
rate=16000,
input=True,
frames_per_buffer=1600
)
# Create a real-time translation session: entering the with context automatically establishes the connection
with client.audio.realtime.connect(
model="qwen3.5-livetranslate-flash-realtime",
) as session:
# Update the session configuration (recommended to call right after the connection is established)
session.update_session(
output_modalities=["text", "audio"],
input_audio_transcription_model="qwen3-asr-flash-realtime",
voice="Tina",
translation_params={
"language": "en", # Translation target language: English
"corpus": {
"phrases": {
"人工智能": "Artificial Intelligence",
"机器学习": "Machine Learning"
}
}
},
)
# Receiving thread: iterate over the server events
def receive_events():
try:
for event in session.events():
event_type = event.get("type", "")
if event_type == "input_audio_buffer.speech_started":
print("====== 检测到语音输入 ======")
elif event_type == "input_audio_buffer.speech_stopped":
print("====== 语音输入结束 ======")
elif event_type == "conversation.item.input_audio_transcription.completed":
print(f"[原文] {event.get('transcript', '')}")
elif event_type == "response.audio_transcript.done":
print(f"[翻译结果] {event.get('transcript', '')}")
elif event_type == "response.audio.delta":
audio_b64 = event.get("delta", "")
if audio_b64:
speaker.write(base64.b64decode(audio_b64))
except DashScopeError as e:
print(f"[错误] {e.message}")
with ThreadPoolExecutor(max_workers=1) as pool:
receiver = pool.submit(receive_events)
# Register the exit signal handler
def on_exit(sig, frame):
print("\n[正在退出...]")
session.end_session()
session.close()
mic.stop_stream()
mic.close()
speaker.stop_stream()
speaker.close()
pya.terminate()
sys.exit(0)
signal.signal(signal.SIGINT, on_exit)
print("[开始实时翻译] 请对着麦克风说话,按 Ctrl+C 退出")
# Continuously capture microphone audio and send it (append_audio also accepts raw bytes, encoded automatically)
try:
while True:
audio_data = mic.read(1600, exception_on_overflow=False)
session.append_audio(audio_data)
finally:
session.end_session()
receiver.result()
if __name__ == "__main__":
main()