跳至主要內容

voice.connect()

connect() 方法會建立 WebSocket 或 WebRTC 連線,以進行實時語音對語音通訊。使用 send()answer() 等其他實時功能前,必須先呼叫此方法。

使用範例
使用範例 的直接連結

import { OpenAIRealtimeVoice } from '@mastra/voice-openai-realtime'
import Speaker from '@mastra/node-speaker'

const speaker = new Speaker({
sampleRate: 24100, // Audio sample rate in Hz - standard for high-quality audio on MacBook Pro
channels: 1, // Mono audio output (as opposed to stereo which would be 2)
bitDepth: 16, // Bit depth for audio quality - CD quality standard (16-bit resolution)
})

// Initialize a real-time voice provider
const voice = new OpenAIRealtimeVoice({
realtimeConfig: {
model: 'gpt-5.1-realtime',
apiKey: process.env.OPENAI_API_KEY,
options: {
sessionConfig: {
turn_detection: {
type: 'server_vad',
threshold: 0.6,
silence_duration_ms: 1200,
},
},
},
},
speaker: 'alloy', // Default voice
})
// Connect to the real-time service
await voice.connect()
// Now you can use real-time features
voice.on('speaker', stream => {
stream.pipe(speaker)
})
// With connection options
await voice.connect({
timeout: 10000, // 10 seconds timeout
reconnect: true,
})

參數
參數 的直接連結

options?:

Record<string, unknown>
Provider 專屬的連線選項

傳回值
傳回值 的直接連結

傳回 Promise<void>,並在成功建立連線後 resolve。

Provider 專屬選項
Provider 專屬選項 的直接連結

每個實時語音 Provider 可為 connect() 方法支援不同選項:

OpenAI Realtime
OpenAI Realtime 的直接連結

options?:

Options
設定選項。
Options

timeout?:

number
連線逾時時間(毫秒)

reconnect?:

boolean
連線中斷時是否自動重新連線

配合 CompositeVoice 使用
using-with-compositevoice 的直接連結

使用 CompositeVoice 時,connect() 方法會委派給已設定的實時 Provider:

import { CompositeVoice } from '@mastra/core/voice'
import { OpenAIRealtimeVoice } from '@mastra/voice-openai-realtime'
const realtimeVoice = new OpenAIRealtimeVoice()
const voice = new CompositeVoice({
realtime: realtimeVoice,
})
// This will use the OpenAIRealtimeVoice provider
await voice.connect()

注意事項
注意事項 的直接連結

  • 此方法只由支援語音對語音功能的實時語音 Provider 實作
  • 如在不支援此功能的語音 Provider 上呼叫,系統會記錄警告並立即 resolve
  • 使用 send()answer() 等其他實時方法前,必須先建立連線
  • 使用完語音 instance 後,請呼叫 close() 以妥善清理資源
  • 部分 Provider 可能會在連線中斷時自動重新連線,實際行為視乎其實作方式
  • 連線錯誤通常會作為 exception 拋出,應將其 catch 並處理