How to detect whether a headphone is inserted or removed in JavaScript?

时间秒杀一切 提交于 2019-11-30 15:57:11

问题


Is there any event in JavaScript, I can listen to in browser, through which we can know whether headphones are inserted or removed?

I assume if we are able to iterate over devices of audio output in JavaScript, is there a possibility, we can deduct the change in the number of audio output devices?


回答1:


You can use the following: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices

example:

navigator.mediaDevices.addEventListener('devicechange', () => {
  // Do whatever you need to with the devices
  // Maybe use enumerateDevices() to see what connected
});

You could check the devices already connected from the following or call it on devicechange:

navigator.mediaDevices.enumerateDevices()
  .then(devices => {
    // Check the connected devices
    console.log(devices);  
  });



回答2:


I am using phone-gap plugin for the same

HTML:

<button class="button button-stable" ng-click="checkHeadphone()">

JS:

$scope.checkHeadphone = function () {
        window.plugins.headsetdetection.detect(function (detected) {
            alert("Headphone " + detected)
        })
    }


来源:https://stackoverflow.com/questions/48064757/how-to-detect-whether-a-headphone-is-inserted-or-removed-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!