标签:events javascript
这个问题已经在这里有了答案: > How to detect whether a headphone is inserted or removed in JavaScript? 2个
如果音频设备发生更改,我想暂停视频.例如如果耳机已拔出.有活动吗?
我遇到了其他一些问题,但不适用于浏览器
> Detect if headphones are plugged in or not via C#
> Detecting when head phones are plugged in
> Android: Checking if headphones are plugged in
解决方法:
这不是完美的,并且可能有点笨拙,因为它依赖浏览器公开MediaDevice的label属性,然后尝试使用字符串“ head”来猜测用户是否连接了耳机设备,但是您也可以只需观看连接的音频设备的数量,并在其发生变化或根据您的使用情况而有所不同时暂停.
几乎所有逻辑都从MDN页面改编为navigator.mediaDevices.ondevicechange
.
注意:从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处理程序所需的时间也更长.
标签:events,javascript 来源: https://codeday.me/bug/20191211/2105828.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。