> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # voice.on() `on()` 方法用于注册 Voice 事件监听器。对于实时 Voice Provider,此方法尤其重要,因为它们使用事件来传递转录文本、音频响应和其他状态变化。 ## 使用示例 ```typescript import { OpenAIRealtimeVoice } from '@mastra/voice-openai-realtime' import Speaker from '@mastra/node-speaker' import chalk from 'chalk' // Initialize a real-time voice provider const voice = new OpenAIRealtimeVoice({ realtimeConfig: { model: 'gpt-5.1-realtime', apiKey: process.env.OPENAI_API_KEY, }, }) // Connect to the real-time service await voice.connect() // Register event listener for transcribed text voice.on('writing', event => { if (event.role === 'user') { process.stdout.write(chalk.green(event.text)) } else { process.stdout.write(chalk.blue(event.text)) } }) // Listen for audio data and play it const speaker = new Speaker({ sampleRate: 24100, channels: 1, bitDepth: 16, }) voice.on('speaker', stream => { stream.pipe(speaker) }) // Register event listener for errors voice.on('error', ({ message, code, details }) => { console.error(`Error ${code}: ${message}`, details) }) ``` ## 参数 **event** (`string`): 要监听的事件名称。可用事件列表请参阅 Voice 事件文档。 **callback** (`function`): 事件发生时调用的回调函数。callback 签名取决于具体事件。 ## 返回值 此方法不返回值。 ## 事件 有关事件及其 payload 结构的详细列表,请参阅 [Voice 事件](https://mastra.zisheng.pro/reference/voice/voice.events)文档。 常见事件包括: - `speaking`:有音频数据可用时发出 - `speaker`:随可输送到音频输出的流一起发出 - `writing`:转录或生成文本时发出 - `error`:发生错误时发出 - `tool-call-start`:即将执行 Tool 时发出 - `tool-call-result`:Tool 执行完成时发出 不同 Voice Provider 可能支持不同的事件集合,其 payload 结构也可能有所差异。 ## 与 `CompositeVoice` 配合使用 使用 `CompositeVoice` 时,`on()` 方法会委托给已配置的实时 Provider: ```typescript import { CompositeVoice } from '@mastra/core/voice' 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) }) const realtimeVoice = new OpenAIRealtimeVoice() const voice = new CompositeVoice({ realtime: realtimeVoice, }) // Connect to the real-time service await voice.connect() // This will register the event listener with the OpenAIRealtimeVoice provider voice.on('speaker', stream => { stream.pipe(speaker) }) ``` ## 注意事项 - 此方法主要用于支持事件式通信的实时 Voice Provider - 如果在不支持事件的 Voice Provider 上调用此方法,它会记录警告且不执行任何操作 - 应在调用可能发出事件的方法之前注册事件监听器 - 要移除事件监听器,请使用 [voice.off()](https://mastra.zisheng.pro/reference/voice/voice.off) 方法,并传入相同的事件名称和回调函数 - 可以为同一事件注册多个监听器 - callback 函数会根据事件类型接收不同的数据(请参阅 [Voice 事件](https://mastra.zisheng.pro/reference/voice/voice.events)) - 为获得最佳性能,不再需要事件监听器时,建议将其移除