[英]Javascript windows - Add a listener for speaker and microphone event
我想将事件侦听器绑定到检查浏览器是否正在使用扬声器和麦克风的 Windows 对象。
我的用例如下:我有一个应用程序,用户可以在其中录制音频并进行播放。 但是,如果应用程序已空闲 60 秒,那么我希望它重新加载。
我已将侦听器添加到mousemove
和keypress
以防止应用程序在被调用时重新加载,但我也想在用户录制音频或播放音频时防止重新加载。
我能想到的方法是为这些情况添加类似的事件监听器(录制+播放),但我不知道如何为它们添加监听器。
我需要类似的东西
windows.addEventListener('speaker', () => console.log('user using speaker')
windows.addEventListener('microphone', () => console.log('user using microphone')
是否存在这样的事件? 或者有什么方法可以检查浏览器是否正在使用扬声器+麦克风?
任何线索将不胜感激!
不,没有microphone
或speaker
事件。
但! 您可以使用Event
构造函数创建自己的事件。 我在这里做了一个例子,它创建了一个microphonestart
开始和microphonestop
事件。 每当麦克风 stream 启动或 stream 停止时,都会发出这些事件。
async function getMicrophone() {
// Use audio only.
const constraints = { audio: true };
// Create the events.
const microphoneStartEvent = new Event('microphonestart');
const microphoneStopEvent = new Event('microphonestop');
// Internal function to stop the stream and fire the microphonestop event.
const stopStream = stream => {
const tracks = stream.getAudioTracks();
for (const track of tracks) {
track.stop();
}
window.dispatchEvent(microphoneStopEvent);
}
// Create the stream.
const stream = await navigator.mediaDevices.getUserMedia(constraints);
// You'll want to know if a stream has randomly stopped without the user's intent.
const tracks = stream.getAudioTracks();
for (const track of tracks) {
track.addEventListener('ended', () => {
window.dispatchEvent(microphoneStopEvent);
});
}
// Stream is running, fire microphonestart event.
window.dispatchEvent(microphoneStartEvent);
// Return both the stream and the stopStream function.
return {
stream,
stopStream
};
}
现在您可以像您的示例一样使用它,期望现在有两个事件,开始和停止。 但我认为这只会让你更容易知道你的空闲逻辑何时开始和停止。
// Listen to the microphonestart event.
window.addEventListener('microphonestart', () => {
console.log('user using microphone');
});
// Listen to the microphonestop event.
window.addEventListener('microphonestop', () => {
console.log('user stopped using microphone');
});
// Start the stream.
getMicrophone().then(({ stream, stopStream }) => {
// Use the stream.
console.log(stream);
// Stop the stream when you need.
stopStream(stream);
}).catch(error => {
// Catch your error.
});
至于你的扬声器; 这是相同的原理。 但是,它确实取决于您使用的技术。 您使用的是HTMLAudioElement
还是 Web 音频 API?
我想将其用于我的项目。 但是,当我运行它时,控制台中显示的只是“用户停止使用麦克风”。 如果我点击麦克风或播放音乐,则不会被检测到。 怎么了?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.