我是getusermedia
的初学者,只是从Google获得了一些代码,我能够处理这些代码。但我必须在我的webapp上显示选项,用户可以从主要(笔记本电脑)或辅助(通过USB连接)选择WebCam。
试过这个,为小学(笔记本电脑WebCam)工作,但是当我添加USB WebCam时,它是自动选择USB WebCam。
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);
});
是否可以,我可以显示两个网络摄像头的选项。
由于
答案 0 :(得分:1)
函数navigator.getUserMedia()
只会为您提供默认摄像头(Firefox除外,它可以选择与Web应用程序共享哪个摄像头)
要避免此问题,您应该使用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