Javascript 通过getusermedia选择网络摄像头

Javascript 通过getusermedia选择网络摄像头,javascript,getusermedia,Javascript,Getusermedia,我是getusermedia的初学者,刚从谷歌获得一些代码,我能够处理这些代码。但我必须在我的webapp上显示选项,用户可以在其中从主(笔记本电脑)或辅助(通过USB连接)选择网络摄像头 尝试了这个,主要工作(笔记本电脑网络摄像头),但当我添加USB网络摄像头,它是自动选择USB网络摄像头 var canvas = document.getElementById("canvas"), context = canvas.getContext("2d"), video = document.get

我是
getusermedia
的初学者,刚从谷歌获得一些代码,我能够处理这些代码。但我必须在我的webapp上显示选项,用户可以在其中从主(笔记本电脑)或辅助(通过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除外,它提供了与web应用程序共享哪个摄像头的选项)

要避免此问题,应使用
navigator.mediaDevices.enumerateDevices()
,然后使用
navigator.mediaDevices.getUserMedia(约束)

示例:

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) {
    // ...
  }
上述函数使用
承诺
,需要比您更复杂的方法。所以你需要做一些阅读来适应这种方法。查看下面的链接以获取一些示例: