I have the following code to fill up a select
with the available microphones
JavaScript
x
31
31
1
const audioInputSelect = document.querySelector('select#audioSource');
2
3
// Updates the select element with the provided set of cameras
4
function updateMicrophoneList(microphones) {
5
console.log(microphones);
6
audioInputSelect.innerHTML = '';
7
microphones.map(microphone => {
8
const microphoneOption = document.createElement('option');
9
microphoneOption.label = microphone.label;
10
microphoneOption.value = microphone.deviceId;
11
}).forEach(microphoneOption => audioInputSelect.add(microphoneOption));
12
}
13
14
15
// Fetch an array of devices of a certain type
16
async function getConnectedDevices(type) {
17
const devices = await navigator.mediaDevices.enumerateDevices();
18
return devices.filter(device => device.kind === type)
19
}
20
21
22
// Get the initial set of cameras connected
23
const microphonesList = getConnectedDevices('audioinput');
24
updateMicrophoneList(microphonesList);
25
26
// Listen for changes to media devices and update the list accordingly
27
navigator.mediaDevices.addEventListener('devicechange', event => {
28
const newMicrophoneList = getConnectedDevices('audioinput');
29
updateMicrophoneList(newMicrophoneList);
30
});
31
I’m getting the error
JavaScript
1
4
1
VM1759 audio_devices.js:7 Uncaught TypeError: microphones.map is not a function
2
at updateMicrophoneList (VM1759 audio_devices.js:7)
3
at VM1759 audio_devices.js:24
4
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.
JavaScript
1
2
1
getConnectedDevices('audioinput').then(updateMicrophoneList);
2