我是 getusermedia
的新手,刚刚从 Google 获得了一些代码,我可以处理这些代码。但我必须在我的网络应用程序上显示选项,用户可以从中选择主要(笔记本电脑)或次要(通过 USB 连接)的网络摄像头。
试过这个,适用于主要(笔记本电脑网络摄像头),但是当我添加 USB 网络摄像头时,它会自动选择 USB 网络摄像头。
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
imagegrid = document.getElementById("imagegrid"),
videoObj = { "video": true },
errBack = function(error) {
console.log("Video capture error: ", error.code);
};
var video = document.querySelector("#video");
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({video: true}, handleVideo, videoError);
}
function handleVideo(stream) {
video.src = window.URL.createObjectURL(stream);
}
function videoError(e) {
// do something
}
// Trigger photo take
document.getElementById("video").addEventListener("click", function() {
draw(video, canvas, imagegrid);
});
是否可能,我可以显示两个网络摄像头的选项。
谢谢
最佳答案
navigator.getUserMedia()
函数只会为您提供默认摄像头(Firefox 除外,它让您可以选择与网络应用程序共享哪个摄像头)
要避免此问题,您应该使用 navigator.mediaDevices.enumerateDevices()
,然后使用 navigator.mediaDevices.getUserMedia(constraints)
。
示例:
navigator.mediaDevices.enumerateDevices()
.then(gotDevices)
.catch(errorCallback);
...
function gotDevices(deviceInfos) {
...
for (var i = 0; i !== deviceInfos.length; ++i) {
var deviceInfo = deviceInfos[i];
var option = document.createElement('option');
option.value = deviceInfo.deviceId;
if (deviceInfo.kind === 'audioinput') {
option.text = deviceInfo.label ||
'Microphone ' + (audioInputSelect.length + 1);
audioInputSelect.appendChild(option);
} else if (deviceInfo.kind === 'audiooutput') {
option.text = deviceInfo.label || 'Speaker ' +
(audioOutputSelect.length + 1);
audioOutputSelect.appendChild(option);
} else if (deviceInfo.kind === 'videoinput') {
option.text = deviceInfo.label || 'Camera ' +
(videoSelect.length + 1);
videoSelect.appendChild(option);
}
...
}
navigator.mediaDevices.getUserMedia(constraints)
.then(function(stream) {
var videoTracks = stream.getVideoTracks();
console.log('Got stream with constraints:', constraints);
console.log('Using video device: ' + videoTracks[0].label);
stream.onended = function() {
console.log('Stream ended');
};
window.stream = stream; // make variable available to console
video.srcObject = stream;
})
.catch(function(error) {
// ...
}
上述函数使用promises
并且需要比您的更复杂的方法。所以你需要做一些阅读以适应这种方法。查看下面的链接以获取一些示例:
https://developers.google.com/web/updates/2015/10/media-devices
关于javascript - 通过 getusermedia 选择网络摄像头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49167384/