JavaScript如何检测耳机是否插入或拔出?

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

有没有JavaScript中的事件,我可以在浏览器中监听,通过它可以知道耳机是否插入或取出?

我假设如果我们能够在 JavaScript 中迭代音频输出设备,是否有可能,我们可以扣除音频输出设备数量的变化?

您可以使用以下内容:https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices

示例:

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

您可以从以下查看已连接的设备或在devicechange上调用它:

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

我正在使用 phone-gap 插件

HTML:

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

JS:

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