How to subtract inserted / removed headphones in javascript?

Are there any events in JavaScript that I can listen to in the browser through which we can find out if the headphones are inserted or removed?

I assume that if we can iterate over audio output devices in JavaScript, is there any way we can subtract the change in the number of audio output devices?

+4
source share
2 answers

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 can check already connected devices from the following or call it devicechange:

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

I use the 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
source

Source: https://habr.com/ru/post/1691630/


All Articles