如何从相机复制HTML5视频流

时间:2017-04-18 15:08:01

标签: html5 video

我想在三个盒子中并行显示相同的摄像机视频。因此我有以下代码:

<body>
<!-- HTML5 video to play/stream the camera recording. -->
<video height="360" width="480" autoplay></video><br>
<video height="360" width="480" autoplay></video><br>
<video height="360" width="480" autoplay></video>

<!--Script to get the video source-->
<script>
    // Reference to video element.
  var video = document.querySelector('video');

    var errorCallback = function(e) {
        // User rejected camera request. Handle appropriately.
    };

    // Ensure cross-browser functionality.
    navigator.getUserMedia  = navigator.getUserMedia ||
                              navigator.webkitGetUserMedia ||
                              navigator.mozGetUserMedia ||
                              navigator.msGetUserMedia;

    if (navigator.getUserMedia) {
        navigator.getUserMedia({audio: false, video: true}, function(stream) {
            video.src = window.URL.createObjectURL(stream);
        }, errorCallback);
    } else {
      video.src = 'errorVideo.webm'; // fallback.
    }
</script>

当前结果是左上角的一个视频和显示视频下的两个“空白区域”。我还需要更改以在两个区域播放顶级视频吗?是否还有this以外的其他文档?

1 个答案:

答案 0 :(得分:2)

使用querySelectorAll获取DOM中的所有video元素( querySelector仅返回第一个),然后迭代( with a loop )在集合上,并将源分配给所有相关元素。

// Reference to video element.
var videos = document.querySelectorAll('video');

var errorCallback = function(e) {
  // User rejected camera request. Handle appropriately.
};

// Ensure cross-browser functionality.
navigator.getUserMedia = navigator.getUserMedia ||
  navigator.webkitGetUserMedia ||
  navigator.mozGetUserMedia ||
  navigator.msGetUserMedia;

if (navigator.getUserMedia) {
  navigator.getUserMedia({
    audio: false,
    video: true
  }, function(stream) {
    for (var i = 0; i < videos.length; i++) {
      videos[i].src = window.URL.createObjectURL(stream);
    }

  }, errorCallback);
} else {
  for (var i = 0; i < videos.length; i++) {
    videos[i].src = 'errorVideo.webm'; // fallback.
  }

}
<video height="360" width="480" autoplay></video><br>
<video height="360" width="480" autoplay></video><br>
<video height="360" width="480" autoplay></video>