8

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?

TheParam
  • 10,113
  • 4
  • 40
  • 51
sarathprasath
  • 589
  • 1
  • 8
  • 20
  • Check this https://developer.mozilla.org/en-US/docs/Web/API/BaseAudioContext/destination and this https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API – Rishikesh Chandra Jan 02 '18 at 17:03

2 Answers2

8

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);  
  });
Rick
  • 897
  • 6
  • 14
0

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