首页 > 解决方案 > 获取所有可用的麦克风 - 地图不是功能

问题描述

我有以下代码来填充select可用的麦克风

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);
});

我收到错误

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

为什么map在这里不起作用?

标签: javascript

解决方案


getConnectedDevices是一个异步函数,这意味着它返回一个 Promise 而不是一个数组。当 Promise 完成时,您可以使用该.then功能更新列表。

getConnectedDevices('audioinput').then(updateMicrophoneList);

推荐阅读