voice.off()
off() 方法会移除之前通过 on() 方法注册的事件监听器。这对于清理资源以及防止在具有实时语音功能的长时间运行应用中发生内存泄漏特别有用。
🌐 The off() method removes event listeners previously registered with the on() method. This is particularly useful for cleaning up resources and preventing memory leaks in long-running applications with real-time voice capabilities.
使用示例Direct link to 使用示例
🌐 Usage Example
import { OpenAIRealtimeVoice } from "@mastra/voice-openai-realtime";
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();
// Define the callback function
const writingCallback = ({ text, role }) => {
if (role === "user") {
process.stdout.write(chalk.green(text));
} else {
process.stdout.write(chalk.blue(text));
}
};
// Register event listener
voice.on("writing", writingCallback);
// Later, when you want to remove the listener
voice.off("writing", writingCallback);
参数Direct link to 参数
🌐 Parameters
event:
string
Name of the event to stop listening for (e.g., 'speaking', 'writing', 'error')
callback:
function
The same callback function that was passed to on()
返回值Direct link to 返回值
🌐 Return Value
此方法不返回值。
🌐 This method does not return a value.
注意Direct link to 注意
🌐 Notes
- 传递给
off()的回调必须是传递给on()的相同函数引用 - 如果未找到回调,该方法将不会产生任何效果
- 这种方法主要用于支持基于事件通信的实时语音提供商
- 如果调用了不支持事件的语音提供商,它会记录一条警告并且不会执行任何操作
- 移除事件监听器对于防止长时间运行的应用出现内存泄漏非常重要