> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # voice.on() `on()` 方法會為語音事件註冊事件 listener。這對實時語音 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 函數。callback signature 視乎個別事件。 ## 傳回值 此方法不會傳回值。 ## 事件 如欲查看詳細事件清單及其 payload 結構,請參閱 [Voice 事件](https://mastra.zisheng.pro/zh-HK/reference/voice/voice.events)文件。 常見事件包括: - `speaking`:有音訊資料可用時發出 - `speaker`:發出可 pipe 至音訊輸出的串流 - `writing`:文字經轉錄或產生時發出 - `error`:發生錯誤時發出 - `tool-call-start`:即將執行 Tool 時發出 - `tool-call-result`:Tool 執行完成時發出 不同語音 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) }) ``` ## 注意事項 - 此方法主要用於支援事件式通訊的實時語音 Provider - 如在不支援事件的語音 Provider 上呼叫,系統會記錄警告,而不會執行任何操作 - 應在呼叫任何可能發出事件的方法前註冊事件 listener - 如要移除事件 listener,請使用 [voice.off()](https://mastra.zisheng.pro/zh-HK/reference/voice/voice.off) 方法,並傳入相同的事件名稱及 callback 函數 - 可為同一事件註冊多個 listener - callback 函數會視乎事件類型接收不同資料(請參閱 [Voice 事件](https://mastra.zisheng.pro/zh-HK/reference/voice/voice.events)) - 為獲得最佳效能,請考慮在不再需要事件 listener 時將其移除