如何在浏览器中检查耳机是否刚刚拔出? [英] How to check in browser if the headphones just got plugged out?

查看:390
本文介绍了如何在浏览器中检查耳机是否刚刚拔出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果音频设备发生更改,我想暂停视频.例如如果耳机已拔出.有活动吗?

I want to pause the video if the audio device changes. e.g. if the headphones get plugged out. Is there an event for that?

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

I went through some other questions but they are not for browser

  1. 检测是否插入了耳机或不是通过C#
  2. 检测何时插入头戴式耳机
  3. Android:检查是否插入了耳机
  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

推荐答案

这不是十全十美的,因为它依赖于浏览器公开MediaDevicelabel属性,然后尝试使用字符串"head"来猜测用户是否已连接了耳机设备,但是您也可以仅观看已连接的音频设备的数量,并在音频设备发生任何变化或因使用情况而定时暂停播放.

This isn't perfect and it might be a little hacky since it relies on the browser exposing the label attribute of the MediaDevice and then trying to use the string "head"to guess if the user has a headphone device connected, but you could also just watch the number of connected audio devices and pause whenever it changes or something depending on your usecase.

几乎所有逻辑都从MDN页面改编为 navigator.mediaDevices.ondevicechange .

Almost all of the logic was adapted from the MDN page for navigator.mediaDevices.ondevicechange.

注意:从file:// URL执行时,此代码无法正常工作,必须通过http://https:// URL进行访问,浏览器才能真正访问<MediaDevice的c0>属性.另外,根据您的浏览器,您可能需要使用此答案的第一个迭代版本中的 hack ,这会要求麦克风访问权限的用户,并授予您访问label属性的权限.

NOTE: This code does not work properly when executed from a file:// URL and must be accessed via an http:// or https:// URL for the browser to actually let you access the label property of the MediaDevice. Also, depending on your browser, you may need to use the hack featured in the first iteration of this answer which will ask the user for microphone access and grant you access to the label property.

// 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处理程序所花费的时间也比其他浏览器长.

NOTE: Testing has been spotty with this new, simpler version, but it eliminates the microphone access requirement. Some browsers also take longer to trigger the ondevicechange handler than others.

这篇关于如何在浏览器中检查耳机是否刚刚拔出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆