ErikWe
ErikWe

Reputation: 191

How to duplicate HTML5 video stream from camera

I want to display the same camera video parallel in three boxes. Therefore i have the following code:

<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>

The current result is one video in the top-left corner and two "empty areas" under the displayed video. What do i need to change to play the top video in the two areas as well? Is there any further documentation than this?

Upvotes: 0

Views: 1624

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196296

Use querySelectorAll to get all video elements in the DOM (querySelector only returns the first one) and then iterate (with a loop) over the collections and assign the source to all relevant elements.

// 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>

Upvotes: 2

Related Questions