建立 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'])。开启设备指纹绑定的令牌不支持这种方式。