如何在浏览器中检查耳机是否刚刚拔出?

Sou*_*nda 5 javascript events

如果音频设备发生变化,我想暂停视频。例如,如果耳机被拔掉。有这样的活动吗?

我遇到了其他一些问题,但它们不适用于浏览器

  1. 通过C#检测耳机是否插入
  2. 检测耳机何时插入
  3. Android:检查耳机是否已插入

Eri*_*len 3

这并不完美,而且可能有点 hacky,因为它依赖于浏览器公开 的label属性MediaDevice,然后尝试使用该字符串"head"来猜测用户是否连接了耳机设备,但您也可以只查看连接的音频设备并在其发生变化或根据您的使用情况发生变化时暂停。

几乎所有逻辑均改编自 MDN 页面navigator.mediaDevices.ondevicechange

注意:当从 URL 执行时,此代码无法正常工作file://,必须通过浏览器的http://或URL 进行访问,才能真正让您访问. 此外,根据您的浏览器,您可能需要使用此答案的第一次迭代中的黑客功能,这将要求用户访问麦克风并授予您访问该属性的权限。https://labelMediaDevicelabel

// 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;
Run Code Online (Sandbox Code Playgroud)

注意:这个新的、更简单的版本的测试不稳定,但它消除了麦克风访问要求。某些浏览器触发处理程序的时间也比其他浏览器长ondevicechange