I want to pause the video if the audio device changes. e.g. if the headphones get plugged out. Is there an event for that?
I went through some other questions but they are not for browser
I want to pause the video if the audio device changes. e.g. if the headphones get plugged out. Is there an event for that?
I went through some other questions but they are not for browser
This isn't perfect and it might be a little hacky since it relies on the browser exposing the label
attribute of the MediaDevice
and then trying to use the string "head"
to guess if the user has a headphone device connected, but you could also just watch the number of connected audio devices and pause whenever it changes or something depending on your usecase.
Almost all of the logic was adapted from the MDN page for navigator.mediaDevices.ondevicechange
.
NOTE: This code does not work properly when executed from a file://
URL and must be accessed via an http://
or https://
URL for the browser to actually let you access the label
property of the MediaDevice
. Also, depending on your browser, you may need to use the hack featured in the first iteration of this answer which will ask the user for microphone access and grant you access to the label
property.
// let's assume we don't have any headphones connected
let headphonesConnected = false;
const updateDevices = () => {
navigator.mediaDevices.enumerateDevices()
.then(function(devices) {
// check to see if we have any device with "head" in its name connected
// like "headset" or "headphones"
headphonesConnected = devices
.filter(device => /audio\w+/.test(device.kind))
.find(device => device.label.toLowerCase().includes('head'))
;
})
;
};
updateDevices();
// add an ondevicechange event listener so we can tell when
// an input device is connected and disconnected
navigator.mediaDevices.ondevicechange = updateDevices;
NOTE: Testing has been spotty with this new, simpler version, but it eliminates the microphone access requirement. Some browsers also take longer to trigger the ondevicechange
handler than others.