Skip to main content

Qwen-Audio-Realtime Ruby SDK

Ruby SDK で Qwen-Audio-Realtime に録音を送信し、応答音声を保存します。

前提条件

Ruby SDK をインストールし、API キーを設定します。WorkspaceId をシンガポールのワークスペース ID に置き換え、同じリージョンの API キーを使用します。

クイックスタート

サンプルを 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

SDK リファレンス

オプション説明
model, url, voiceモデル ID、Realtime WebSocket エンドポイント、モデルがサポートする音声です。
turn_detection_modeターン検出モードです。デフォルトは :server_vad です。:push_to_talk モードでは、アプリが応答を開始します。
モデルごとの値と制限については、API リファレンスをご参照ください。 connect で接続し、pump でイベントを読み取ります。session.updated を受け取ってから、append_audio で音声を送信します。on_response_completed を受け取ったら、finish を呼び出してセッションを閉じます。 16 kHz、16 ビット、モノラルの raw PCM を入力します。モデルがサポートする voice を選択します。末尾に無音を加えると、サーバー側の VAD がターンの終了を検出できます。