<分区>
如果音频设备发生变化,我想暂停视频。例如如果耳机被拔掉。有这样的事件吗?
我经历了一些其他问题,但它们不适用于浏览器
标签 javascript events
<分区>
如果音频设备发生变化,我想暂停视频。例如如果耳机被拔掉。有这样的事件吗?
我经历了一些其他问题,但它们不适用于浏览器
最佳答案
这并不完美,它可能有点老套,因为它依赖于浏览器公开 MediaDevice
的 label
属性,然后尝试使用字符串 “head”
猜测用户是否连接了耳机设备,但您也可以只观察连接的音频设备的数量,并在它发生变化时暂停或根据您的使用情况暂停。
几乎所有逻辑都改编自 navigator.mediaDevices.ondevicechange
的 MDN 页面.
注意:当从 file://
URL 执行时,此代码无法正常工作,必须通过 http://
访问> 或 https://
浏览器的 URL,以实际让您访问 MediaDevice
的 label
属性。此外,根据您的浏览器,您可能需要使用 hack featured in the first iteration of this answer这将要求用户访问麦克风并授予您访问 label
属性的权限。
// let's assume we don't have any headphones connected
let headphonesConnected = false;
const updateDevices = () => {
navigator.mediaDevices.enumerateDevices()
.then(function(devices) {
// check to see if we have any device with "head" in its name connected
// like "headset" or "headphones"
headphonesConnected = devices
.filter(device => /audio\w+/.test(device.kind))
.find(device => device.label.toLowerCase().includes('head'))
;
})
;
};
updateDevices();
// add an ondevicechange event listener so we can tell when
// an input device is connected and disconnected
navigator.mediaDevices.ondevicechange = updateDevices;
注意:这个新的、更简单的版本的测试一直不稳定,但它消除了麦克风访问要求。一些浏览器还需要比其他浏览器更长的时间来触发 ondevicechange
处理程序。
关于javascript - 如果耳机刚拔出,如何在浏览器中检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55073392/