Skip to content

Instantly share code, notes, and snippets.

@chetbox
Last active May 11, 2022 10:08
Show Gist options
  • Save chetbox/5aba04852c5a2052fe3bd9b847b6f352 to your computer and use it in GitHub Desktop.
Save chetbox/5aba04852c5a2052fe3bd9b847b6f352 to your computer and use it in GitHub Desktop.
Browser audio output switching
<!DOCTYPE html>
<html>
<body>
<button>
Play/pause
</button>
<script>
const audioElement = document.createElement('audio');
audioElement.src = 'http://www.jamesreams.com/wp-content/uploads/2013/01/30-Sec-Acre.mp3';
audioElement.autoplay = true;
document.body.appendChild(audioElement);
document.querySelector('button').addEventListener('click', () => {
if (audioElement.paused) {
audioElement.play();
} else {
audioElement.pause();
}
});
const option = document.createElement('option');
option.value = '';
option.innerText = 'None';
const outputPicker = document.createElement('select');
async function updatePicker() {
const devices = await navigator.mediaDevices.enumerateDevices();
console.log('devices', devices);
const audioDevices = devices.filter(device => device.kind === 'audiooutput');
outputPicker.replaceChildren();
for (const device of audioDevices) {
const option = document.createElement('option');
option.value = device.deviceId;
option.innerText = JSON.stringify(device.label) + ' - ' + device.groupId;
outputPicker.appendChild(option);
}
document.body.appendChild(outputPicker);
outputPicker.addEventListener('change', (e) => {
console.log('Selected', JSON.stringify(e.target.value));
audioElement.setSinkId(e.target.value);
})
}
navigator.mediaDevices.addEventListener('devicechange', updatePicker);
updatePicker();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment