I have the following code to fill up a select
with the available microphones
const audioInputSelect = document.querySelector('select#audioSource'); // Updates the select element with the provided set of cameras function updateMicrophoneList(microphones) { console.log(microphones); audioInputSelect.innerHTML = ''; microphones.map(microphone => { const microphoneOption = document.createElement('option'); microphoneOption.label = microphone.label; microphoneOption.value = microphone.deviceId; }).forEach(microphoneOption => audioInputSelect.add(microphoneOption)); } // Fetch an array of devices of a certain type async function getConnectedDevices(type) { const devices = await navigator.mediaDevices.enumerateDevices(); return devices.filter(device => device.kind === type) } // Get the initial set of cameras connected const microphonesList = getConnectedDevices('audioinput'); updateMicrophoneList(microphonesList); // Listen for changes to media devices and update the list accordingly navigator.mediaDevices.addEventListener('devicechange', event => { const newMicrophoneList = getConnectedDevices('audioinput'); updateMicrophoneList(newMicrophoneList); });
I’m getting the error
VM1759 audio_devices.js:7 Uncaught TypeError: microphones.map is not a function at updateMicrophoneList (VM1759 audio_devices.js:7) at VM1759 audio_devices.js:24
Why doesn’t map
work here?
Advertisement
Answer
getConnectedDevices
is an async function, meaning that it returns a Promise instead of an array. You can use the .then
function to update the list when the Promise is fulfilled.
getConnectedDevices('audioinput').then(updateMicrophoneList);