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

前端 未结 2 1334
别那么骄傲
别那么骄傲 2021-01-01 03:05

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 iterat

相关标签:
2条回答
  • 2021-01-01 03:14

    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)
            })
        }
    
    0 讨论(0)
  • 2021-01-01 03:25

    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);  
      });
    
    0 讨论(0)
提交回复
热议问题