使用以下代码获取所有可用的麦克风,并使用该列表更新选择器。
const audioInputSelect = document.querySelector('select#audioSource');
// Updates the select element with the provided set of cameras
function updateMicrophoneList(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)
}
getConnectedDevices('audioinput').then(microphonesList => updateMicrophoneList(microphonesList));获取错误:
audio_devices.js:11 Uncaught (in promise) TypeError: Failed to execute 'add' on 'HTMLSelectElement': The provided value is not of type '(HTMLOptionElement or HTMLOptGroupElement)'
at audio_devices.js:11
at Array.forEach (<anonymous>)
at updateMicrophoneList (audio_devices.js:11)
at audio_devices.js:21如何强制document.createElement('option')创建所需类型的元素?
发布于 2021-03-03 19:49:13
选项上没有"label“,您需要对选项进行return
audioInputSelect.innerHTML = '';
microphones.map(microphone => {
const microphoneOption = document.createElement('option');
microphoneOption.textContent = microphone.label;
microphoneOption.value = microphone.deviceId;
return microphoneOption;
}).forEach(microphoneOption => audioInputSelect.add(microphoneOption));或
audioInputSelect.innerHTML = '';
microphones.map(microphone => {
const microphoneOption = document.createElement('option');
microphoneOption.textContent = microphone.label;
microphoneOption.value = microphone.deviceId;
audioInputSelect.add(microphoneOption);
})但这更短更快
audioInputSelect.innerHTML = microphones
.map(({deviceId, label }) => `<option value="${deviceId}">${label}</options>`)
.join("");https://stackoverflow.com/questions/66456320
复制相似问题