Skip to main content

Qwen-LiveTranslate-Realtime Ruby SDK

使用 Ruby SDK 調用 Qwen-LiveTranslate-Realtime,將中文錄音實時翻譯成英文並打印譯文。

前提條件

按 Ruby SDK 安裝說明 安裝 SDK 並配置 API Key。將示例中的 WorkspaceId 替換為新加坡的業務空間 ID,使用同地域的 API Key。

快速開始

將示例保存為 example.rb,運行 ruby example.rb。
require 'dashscope'

def send_frame(client, frame, interval)
  deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + interval
  client.append_audio(frame)
  while (remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)).positive?
    client.pump(remaining)
  end
end

client = DashScope::Qwen::Translator.new(
  model: 'qwen3.5-livetranslate-flash-realtime',
  url: 'wss://WorkspaceId.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime',
  source_language: 'zh',
  target_language: 'en'
)
client.on_translation_completed = ->(text, _) { puts text }
session_updated = false
client.on_raw_event = ->(type, _) { session_updated = true if type == 'session.updated' }
client.connect
client.pump_until(10) { session_updated }
unless session_updated
  client.abort
  raise 'Timed out waiting for session.updated.'
end
File.open('input.pcm', 'rb') do |input|
  while (frame = input.read(640))
  send_frame(client, frame, 0.02)
  end
end
client.finish

接口說明

參數說明
model, url翻譯模型 ID 和實時 WebSocket 地址。
source_language, target_language源語種和目標語種。
voice翻譯語音使用的音色,按模型支援選擇。
模型的參數取值和限制見接口參考。 呼叫 connect 建立連線後,用 pump 讀取事件。收到 session.updated 後,再用 append_audio 傳送音訊。on_translation_completed 傳回定稿。調用 finish 等待最後一段譯文。 輸入檔案使用 16 kHz、16 位、單聲道原始 PCM。source_language 和 target_language 按所選模型支援的語言填寫。