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

喜欢而已 提交于 2019-11-30 16:25:24

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);  
  });

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