> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # voice.connect() `connect()` 方法建立 WebSocket 或 WebRTC 连接,用于实时语音对语音通信。在使用 `send()` 或 `answer()` 等其他实时功能之前,必须调用此方法。 ## 使用示例 ```typescript 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`): Provider 特定的连接选项 ## 返回值 返回 `Promise`,在连接成功建立后完成。 ## Provider 特定选项 每个实时 Voice Provider 为 `connect()` 方法支持的选项可能不同: ### OpenAI Realtime **options** (`Options`): 配置选项。 **options.timeout** (`number`): 连接超时时间(毫秒) **options.reconnect** (`boolean`): 连接中断时是否自动重新连接 ## 与 `CompositeVoice` 一起使用 使用 `CompositeVoice` 时,`connect()` 方法会委托给已配置的实时 Provider: ```typescript 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() ``` ## 注意事项 - 只有支持语音对语音功能的实时 Voice Provider 才实现此方法 - 如果在不支持此功能的 Voice Provider 上调用此方法,它会记录警告并立即完成 - 使用 `send()` 或 `answer()` 等其他实时方法之前,必须先建立连接 - 使用完 Voice 实例后,请调用 `close()` 以正确清理资源 - 某些 Provider 可能会在连接中断时自动重新连接,具体取决于其实现 - 连接错误通常会作为异常抛出,应对其进行捕获和处理 ## 相关方法 - [voice.send()](https://mastra.zisheng.pro/reference/voice/voice.send):向 Voice Provider 发送音频数据 - [voice.answer()](https://mastra.zisheng.pro/reference/voice/voice.answer):触发 Voice Provider 进行响应 - [voice.close()](https://mastra.zisheng.pro/reference/voice/voice.close):断开与实时服务的连接 - [voice.on()](https://mastra.zisheng.pro/reference/voice/voice.on):为语音事件注册事件监听器