Skip to main content

Qwen-Audio-Realtime Ruby SDK

使用 Ruby SDK 調用 Qwen-Audio-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::Conversation.new(
  model: 'qwen-audio-3.1-realtime-plus',
  url: 'wss://WorkspaceId.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime',
  voice: 'longanfengyue_v3.1'
)
done = false
client.on_response_completed = ->(_) { done = true }

File.open('output.pcm', 'wb') do |output|
  client.on_assistant_audio_chunk = ->(pcm) { output.write(pcm) }
  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
  10.times do
    send_frame(client, "\0" * 3200, 0.1)
  end
  client.pump_until(45) { done }
  client.finish
end

接口說明

參數說明
model, url, voice模型 ID、實時 WebSocket 地址和模型支援的音色。
turn_detection_mode輪次檢測模式。預設 :server_vad。使用 :push_to_talk 時由應用程式觸發應答。
模型的參數取值和限制見接口參考。 呼叫 connect 建立連線後,用 pump 讀取事件。收到 session.updated 後,再用 append_audio 傳送音訊。收到 on_response_completed 後調用 finish,結束會話。 輸入檔案使用 16 kHz、16 位、單聲道原始 PCM。voice 按前台模型選擇。伺服器端 VAD 可以用結尾靜音判斷一輪輸入結束。