访问多摄像头 javascript getusermedia

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22787549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:46:26  来源:igfitidea点击:

Accessing Multiple camera javascript getusermedia

javascripthtml5-videowebcamgetusermedia

提问by Joshua Frederic

guys i have two cameras that is
-the web camera
-the laptop camera

伙计们,我有两个摄像头
——网络摄像头
——笔记本电脑摄像头

i want to stream those camera in a website
i already have some reference
here is some code that is working on jsfiddle here

我想流中的网站的相机
,我已经有一定的参考
这里是一些代码,正在研究的jsfiddle 这里

<video id="video" width="640" height="480" autoplay></video>
<button id="snap" class="sexyButton">Snap Photo</button>
<canvas id="canvas" width="640" height="480"></canvas>

<script>

    // Put event listeners into place
    window.addEventListener("DOMContentLoaded", function() {
        // Grab elements, create settings, etc.
        var canvas = document.getElementById("canvas"),
            context = canvas.getContext("2d"),
            video = document.getElementById("video"),
            videoObj = { "video": true },
            errBack = function(error) {
                console.log("Video capture error: ", error.code); 
            };

        // Put video listeners into place
        if(navigator.getUserMedia) { // Standard
            navigator.getUserMedia(videoObj, function(stream) {
                video.src = stream;
                video.play();
            }, errBack);
        } else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
            navigator.webkitGetUserMedia(videoObj, function(stream){
                video.src = window.webkitURL.createObjectURL(stream);
                video.play();
            }, errBack);
        } else if(navigator.mozGetUserMedia) { // WebKit-prefixed
            navigator.mozGetUserMedia(videoObj, function(stream){
                video.src = window.URL.createObjectURL(stream);
                video.play();
            }, errBack);
        }

        // Trigger photo take
        document.getElementById("snap").addEventListener("click", function() {
            context.drawImage(video, 0, 0, 640, 480);
        });
    }, false);

</script>

that example can only connects and select 1 camera
i want to select and view two of my camera, any suggestion or solution guys?
you can also give me the JS fiddle

该示例只能连接并选择 1 台摄像机,
我想选择并查看我的两台摄像机,有什么建议或解决方案吗?
你也可以给我 JS 小提琴

回答by J0hj0h

You can create two different streams, one for each camera, and show them simultaneously in two <video>tags.

您可以创建两个不同的流,每个摄像机一个,并在两个<video>标签中同时显示它们。

The list of available devices is available using navigator.mediaDevices.enumerateDevices(). After filtering the resulting list for only videoinputs, you have access to the deviceIds without needing permission from the user.

可用设备列表可使用navigator.mediaDevices.enumerateDevices()。仅针对videoinputs过滤结果列表后,您deviceId无需用户许可即可访问s。

With getUserMediayou can then request a stream from the camera with id camera1Idusing

随着getUserMedia您可以从相机,然后请求流与IDcamera1Id使用

navigator.mediaDevices.getUserMedia({
  video: {
    deviceId: { exact: camera1Id }
  }
});

The resulting streamcan be fed into a <video>(referenced here by vid) by calling vid.srcObject = stream.

stream可以通过调用将结果送入 a <video>(此处引用为vidvid.srcObject = stream

I have done this for two streams from two webcams simultaneously.

我同时对来自两个网络摄像头的两个流进行了此操作。

回答by purplelizard

You cannot access two cameras simultaneously. The API would indicate otherwise, but something underlying seems to prevent it from working as expected. You can verify this by opening https://simpl.info/getusermedia/sources/or http://googlechrome.github.io/webrtc/samples/web/content/getusermedia-source/in two completely seperate windows, despite being able to select two streams only one is active at once - if you pick the same one in both windows, then it shows in both places. The only workaround I was able to do was to flip-flop between the two streams, then draw the video to a canvas. Doing this I was able to do captures at around 1 fps, unfortunately the camera resets between frames, on one of my cameras I had to put in a delay to allow the auto white balance to kick in to get a decent image.

您不能同时访问两个摄像机。API 会另有说明,但潜在的某些东西似乎阻止了它按预期工作。您可以通过打开https://simpl.info/getusermedia/sources/http://googlechrome.github.io/webrtc/samples/web/content/getusermedia-source/来验证这一点在两个完全独立的窗口中,尽管能够选择两个流,但一次只有一个处于活动状态 - 如果您在两个窗口中选择相同的一个,则它会在两个位置显示。我能够做的唯一解决方法是在两个流之间翻转,然后将视频绘制到画布上。这样做我能够以大约 1 fps 的速度进行捕获,不幸的是相机在帧之间重置,在我的其中一台相机上我不得不延迟以允许自动白平衡启动以获得不错的图像。

function webcam() {
if (!navigator.getUserMedia) {
    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
}

if (!navigator.getUserMedia) {
    return alert('getUserMedia not supported in this browser.');
}

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var audioSource;
var cw = Math.floor(canvas.clientWidth / 2);
var ch = Math.floor(canvas.clientHeight/2);
//canvas.width = cw;
//canvas.height = ch;

//off dom video player
var video = document.createElement("video");
video.autoplay="autoplay";
video.addEventListener('playing', function(){
    //delay for settling...
    setTimeout(draw,1000,this,context,(currentSource*canvas.clientWidth/2),cw,ch);
},false);

function captureVideo() {
    console.log("Capturing " + currentSource,videosources[currentSource]);
    var mediaOptions = {
        audio: {
            optional: [{sourceId: audioSource}]
        },
        video: {
            optional: [
                {sourceId: videosources[currentSource].id}
            ]
        }};
    navigator.getUserMedia(mediaOptions, success, errorCallback);
}
var currentSource=0;
var videosources = [];
var lastStream;
function errorCallback(error){
    console.log("navigator.getUserMedia error: ", error);
}
function success(stream) {

    console.log("the stream" + currentSource,stream);
    video.src = window.URL.createObjectURL(stream);
    video.play();
    lastStream=stream;
}
function next(){

    if(lastStream){
        lastStream.stop();
    }
    video.src = "";
    if(currentSource < videosources.length-1){
        currentSource+=1;
    }
    else
    {
        currentSource=0;
    }
    captureVideo();
}
function draw(v,c,l,w,h) {
    if(v.paused || v.ended) return false;
    console.log("drawing",l)
    c.drawImage(v,l,0,w,h);
    setTimeout(next,500);
}

MediaStreamTrack.getSources(function (sourceInfos) {

    for (var i = 0; i != sourceInfos.length; ++i) {
        var sourceInfo = sourceInfos[i];
        if (sourceInfo.kind === 'audio') {
            console.log(sourceInfo.id, sourceInfo.label || 'microphone');
            audioSource=sourceInfo.id;

        } else if (sourceInfo.kind === 'video') {
            console.log(sourceInfo.id, sourceInfo.facing, sourceInfo.label || 'camera');
            videosources.push(sourceInfo);

        } else {
            console.log('Some other kind of source: ', sourceInfo);
        }
    }
console.log("sources",videosources)
    next();
});
}

回答by dajuric

Now, it works (tried it in Chrome 41)!

现在,它可以工作了(在 Chrome 41 中尝试过)!

回答by Dan

I can get multiple cameras working if they are on different USB buses. if they are on the same usb bus they will not work simultaneously for me.

如果它们在不同的 USB 总线上,我可以让多个摄像头工作。如果它们在同一条 USB 总线上,它们将不会同时对我来说有效。