建立 WebSocket 連線
連線 /v1/realtime,在 URL 中指定 model,首次 session.update 設定音色與輪次偵測。
Node.js · ws
import WebSocket from 'ws'
const ws = new WebSocket(
'wss://token.easyapi.com/v1/realtime?model=qwen-audio-3.0-realtime-plus',
['realtime'],
{ headers: { Authorization: `Bearer ${process.env.EASYAPI_API_KEY}` } },
)
ws.on('open', () => {
ws.send(JSON.stringify({
type: 'session.update',
session: {
modalities: ['text', 'audio'],
voice: 'longanqian',
instructions: '你是一位温柔知性的中文语音助手。',
input_audio_format: 'pcm',
output_audio_format: 'pcm',
turn_detection: { type: 'server_vad', threshold: 0.5, silence_duration_ms: 800 },
},
}))
})
ws.on('message', (data) => {
const event = JSON.parse(data)
if (event.type === 'response.audio.delta')
process.stdout.write(Buffer.from(event.delta, 'base64')) // PCM 24kHz 16bit mono
if (event.type === 'response.done')
console.log(event.response?.usage)
})
瀏覽器無法自訂 WebSocket 請求標頭,可把 API Key 放進子協定:new WebSocket(url, ['realtime', 'openai-insecure-api-key.sk-xxx'])。開啟裝置指紋綁定的權杖不支援這種方式。