我一直在使用getusermedia来提取多个摄像头,我用一个单独的.js文件调用它,它工作正常,但我需要选择器标签在页面加载时显示数组中可用的所有选项。我试过onload,但没有工作,如果有任何问题,请告诉我。
<div id="container">
<label for="videoSource">Video source: </label><select id="videoSource"></select>
</div>
外部js文件
var videoSelect = document.querySelector('select#videoSource');
var selectors = [videoSelect];
function gotDevices(deviceInfos) {
// Handles being called several times to update labels. Preserve values.
var values = selectors.map(function(select) {
return select.value;
});
selectors.forEach(function(select) {
while (select.firstChild) {
select.removeChild(select.firstChild);
}
});
for (var i = 0; i !== deviceInfos.length; ++i) {
var deviceInfo = deviceInfos[i];
var option = document.createElement('option');
option.value = deviceInfo.deviceId;
if (deviceInfo.kind === 'videoinput') {
option.text = deviceInfo.label || 'camera ' + (videoSelect.length + 1);
videoSelect.appendChild(option);
} else {
console.log('Some other kind of source/device: ', deviceInfo);
}
}
selectors.forEach(function(select, selectorIndex) {
if (Array.prototype.slice.call(select.childNodes).some(function(n) {
return n.value === values[selectorIndex];
})) {
select.value = values[selectorIndex];
}
});
}
navigator.mediaDevices.enumerateDevices().then(gotDevices).catch(handleError);
// Attach audio output device to video element using device/sink ID.
function attachSinkId(element, sinkId) {
if (typeof element.sinkId !== 'undefined') {
element.setSinkId(sinkId)
.then(function() {
console.log('Success, audio output device attached: ' + sinkId);
})
.catch(function(error) {
var errorMessage = error;
if (error.name === 'SecurityError') {
errorMessage = 'You need to use HTTPS for selecting audio output ' +
'device: ' + error;
}
console.error(errorMessage);
// Jump back to first output device in the list as it's the default.
// audioOutputSelect.selectedIndex = 0;
});
} else {
console.warn('Browser does not support output device selection.');
}
}
function gotStream(stream) {
window.stream = stream; // make stream available to console
videoElement.srcObject = stream;
// Refresh button list in case labels have become available
return navigator.mediaDevices.enumerateDevices();
}
function start() {
if (window.stream) {
window.stream.getTracks().forEach(function(track) {
track.stop();
});
}
var videoSource = videoSelect.value;
var constraints = {
video: {deviceId: videoSource ? {exact: videoSource} : undefined}
};
navigator.mediaDevices.getUserMedia(constraints).
then(gotStream).then(gotDevices).catch(handleError);
}
videoSelect.onchange = start;
start();
我试过的方法,不工作..
function show(){
document.getElementById("videoSource");
}
$(document).ready(function(){
show();
});