如何检测在JavaScript中是否插入了耳机? [英] How to detect whether a headphone is inserted or removed in JavaScript?
问题描述
JavaScript中是否有任何事件,我可以在浏览器中收听,通过它我们可以知道是否插入或卸下了耳机?
Is there any event in JavaScript, I can listen to in browser, through which we can know whether headphones are inserted or removed?
我假设我们能够遍历JavaScript中的音频输出设备,是否有可能减少音频输出设备的数量?
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?
推荐答案
您可以使用以下内容: https://developer.mozilla .org / zh-CN / docs / Web / API / MediaDevices
You can use the following: 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上调用它
:
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);
});
这篇关于如何检测在JavaScript中是否插入了耳机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!