> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # voice.on() `on()` 方法會為語音事件註冊事件監聽器。這對即時語音 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`): 事件發生時所呼叫的回呼函式。回呼的簽章取決於特定事件。 ## 傳回值 此方法不會傳回值。 ## 事件 如需事件及其 payload 結構的詳細清單,請參閱 [Voice 事件](https://mastra.zisheng.pro/zh-TW/reference/voice/voice.events)文件。 常見事件包括: - `speaking`:有可用的音訊資料時發出 - `speaker`:發出可透過管線傳送至音訊輸出的串流 - `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 呼叫此方法,系統會記錄警告且不執行任何動作 - 呼叫可能發出事件的方法前,應先註冊事件監聽器 - 若要移除事件監聽器,請以相同的事件名稱和回呼函式使用 [voice.off()](https://mastra.zisheng.pro/zh-TW/reference/voice/voice.off) 方法 - 同一事件可以註冊多個監聽器 - 回呼函式會依事件類型接收不同的資料(請參閱 [Voice 事件](https://mastra.zisheng.pro/zh-TW/reference/voice/voice.events)) - 為獲得最佳效能,不再需要事件監聽器時,請考慮將其移除