javascript - 获取所有可用的麦克风 - 地图不是功能
问题描述
我有以下代码来填充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
在这里不起作用?
解决方案
getConnectedDevices
是一个异步函数,这意味着它返回一个 Promise 而不是一个数组。当 Promise 完成时,您可以使用该.then
功能更新列表。
getConnectedDevices('audioinput').then(updateMicrophoneList);
推荐阅读
- python - Spyder 的代码分析无法识别 tkinter 导入。有没有办法在不改变 * 到每个项目的情况下改变它?
- vba - 根据 Primarykey ID 查找数据位置
- c++ - std::vector 保留和调整 NUMA 局部性
- html - 媒体查询应该放在类旁边还是全部放在 SCSS 文件的末尾?
- regex - Perl 一个使用正则表达式替换的衬里
- sql - 将 LIKE CASE WHEN 与子查询一起使用时出现 SQL 错误
- javascript - 从 json 制作 javascript 中的字典列表
- react-native - React Native 重构与 Flutter 性能比较
- java - 使用新的 Java 14 Record 功能,是否可以为同一个 Record 创建多个构造函数?
- c++ - 带有 HWND 的 Visual Studio C26462 代码分析警告