全部产品
Search
文档中心

大模型服务平台百炼:Qwen-LiveTranslate-Realtime Python SDK

更新时间:Nov 06, 2026

本文档介绍如何使用 DashScope Python SDK 调用实时音视频翻译(Qwen-LiveTranslate-Realtime)模型。

连接与鉴权参见 WebSocket 接入;事件字段与 JSON 示例参见客户端事件和服务端事件。

前提条件

  1. 安装SDK,确保DashScope SDK版本不低于2.0.1。
  2. 获取与配置 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,可在阿里云百炼控制台的业务空间详情页面查看。现有域名仍可正常使用。

请求参数

关键接口

会话(RealtimeSession)

实时翻译会话通过client.audio.realtime.connect(model=...)创建,进入with上下文时自动建立连接(也可调用会话的connect()方法手动建立)。

方法签名服务端响应事件(通过events()迭代下发)说明
def connect(self) -> "RealtimeSession"

服务端事件

会话已创建

服务端事件

会话配置已更新

和服务端创建连接。进入with上下文时自动调用。

def update_session(self,
    output_modalities: List[str],
    *,
    voice: str = None,
    input_audio_transcription_model: str = None,
    translation_params: Dict[str, Any] = None,
    enable_turn_detection: bool = None,
    **kwargs) -> None:

服务端事件

会话已更新

用于更新会话配置,建议在连接建立后首先调用该方法进行设置。若未调用该方法,系统将使用默认配置。只需关注会话update_session方法涉及的参数。

def end_session(self) -> None

session.finished

服务端完成语音翻译,结束会话

通知服务端结束会话,服务端收到会话结束通知后将完成最后的语音翻译。

def append_audio(self, audio_b64: Union[str, bytes]) -> None

无

将音频数据片段追加到云端输入音频缓冲区,支持Base64字符串或原始bytes(自动编码)。服务端会自动检测语音起止并触发翻译。

def commit(self) -> None

input_audio_buffer.committed

输入音频缓冲区已提交

Manual 模式下,提交之前通过append_audio方法追加到云端缓冲区的音频,服务端收到后自动开始生成翻译响应。VAD 模式下无需调用此方法,服务端会自动提交。

def clear_appended_audio(self) -> None:

input_audio_buffer.cleared

输入音频缓冲区已清空

清空当前云端缓冲区中尚未提交的音频数据。

def close(self) -> None:

无

终止任务,并关闭连接。退出with上下文时自动调用。

session.session_id

无

获取当前任务的session_id(从session.created事件读取)。

session.last_response_id

无

获取最近一次response的response_id(从response.created事件读取)。

事件迭代(events())

服务端会通过事件的方式,将服务端响应事件和数据返回给客户端。在接收线程中迭代会话的events()处理服务端事件,session.finished事件后迭代结束。

error事件会以DashScopeError异常抛出,可在接收线程中使用try/except捕获。

捕获异常后如何继续接收事件

捕获 DashScopeError 后,原来的 events() 迭代已经结束。仅在外层使用 try/except 捕获异常,不会让它自动继续接收事件。

如果 WebSocket 连接仍可用,修正请求后重新调用 events(),或用 recv_event() 逐条接收。连接已关闭时,先重新建连并配置会话,再开始接收。

排查错误原因时,可从异常的 body 读取服务端返回的原始错误事件。

方法签名参数说明
def events(self) -> Iterator[Dict[str, Any]]

event:服务端事件

迭代接收服务端事件(dict),session.finished事件后迭代结束。请由一个接收线程持续消费,不要并发创建多个读取者。

def recv_event(self) -> Optional[Dict[str, Any]]

event:服务端事件

读取一条服务端事件,正常关闭后返回None。

完整示例

以下示例展示如何从麦克风实时录音并进行翻译。

麦克风实时翻译示例代码

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()