代码之家  ›  专栏  ›  技术社区  ›  Souradeep Nanda

如果耳机刚插好,如何在浏览器中检查?

  •  2
  • Souradeep Nanda  · 技术社区  · 7 年前

    如果音频设备更改,我想暂停视频。例如,如果耳机被拔出。有这样的活动吗?

    我还问了一些其他问题,但不是针对浏览器的

    1. Detect if headphones are plugged in or not via C#
    2. Detecting when head phones are plugged in
    3. Android: Checking if headphones are plugged in
    0 回复  |  直到 7 年前
        1
  •  2
  •   Eric Allen    7 年前

    这不是完美的,可能有点黑,因为它依赖于浏览器公开 label 的属性 MediaDevice 然后尝试使用字符串 "head" 猜测用户是否连接了耳机设备,但您也可以查看连接的音频设备的数量,并根据您的使用情况随时暂停。

    几乎所有的逻辑都改编自 navigator.mediaDevices.ondevicechange .

    注释 :当从 file:// 必须通过 http:// https:// 浏览器实际允许您访问 标签 财产 媒体设备 . 另外,根据浏览器的不同,您可能需要使用 hack featured in the first iteration of this answer 它将要求用户访问麦克风并允许您访问 标签 财产。

    // 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 比其他人更善于处理。