-1

I’ve created a minimal WebRTC test site that is able to request the user’s webcam/audio stream, to record it, and to playback the recording after it has been stopped.

Demo: https://output.jsbin.com/tabosipefo/

Edit1: https://jsbin.com/tabosipefo/edit?html,console,output

Since this happens all within one Promise navigator.mediaDevices.getUserMedia(), I was wondering, if it is actually possible to detect and on-going stream and to (a) record it, and (b) to stop and save it.

1 WebRTC does not work in jsbin when in edit view for some reason...

Kalaschnik
  • 769
  • 1
  • 7
  • 21
  • Put `stream` in a global variable? – jib Aug 26 '20 at 01:27
  • Yeah, I did that... I think thats my only solution without any JS framework/library – Kalaschnik Aug 26 '20 at 15:18
  • I don't really understand the problem from your question. What do you mean by "an already running" stream? A stream you created earlier in the same document? Can you give an example? – jib Aug 26 '20 at 19:24

1 Answers1

2

If you use no framework and want to use vanilla JS, your best step is to tack the stream object to the global window.

Preview stream

const showWebcamStream = () => {
  navigator.mediaDevices
    .getUserMedia({ audio: true, video: true })
    .then(stream => {
      window.localStream = stream; // ⭠ tack it to the window object

      // grab the <video> object
      const video = document.querySelector("#video-preview");
      video.srcObject = stream;

      // Display stream
      video.onloadedmetadata = () => video.play();
    })
    .catch(err => console.log(err.name, err.message));
};

Now the video will be displayed within the video element (id: #videp-preview).

Stop Stream(s)

const hideWebcamStream = () => localStream.getTracks().forEach(track => track.stop());

You should put the mediaRecorder in the window object in order to stop it later.

Record Stream

const startWebcamRecorder = () => {
  // check if localStream is in window and if it is active
  if ("localStream" in window && localStream.active) {
    // save the mediaRecorder also to Window in order independently stop it
    window.mediaRecorder = new MediaRecorder(localStream);
    window.dataChunks = [];
    mediaRecorder.start();
    console.log(mediaRecorder.state);
    mediaRecorder.ondataavailable = e => dataChunks.push(e.data);
  }
};

Stop Recording and Preview the recording

You need another video element to playback your recording #video-playback

const stopWebcamRecorder = () => {
  if ("mediaRecorder" in window && mediaRecorder.state === "recording") {
    mediaRecorder.stop();
    console.log(mediaRecorder.state);
    mediaRecorder.onstop = () => {
      let blob = new Blob(dataChunks, { type: "video/mp4;" });
      dataChunks = [];
      let videoURL = window.URL.createObjectURL(blob);
      const videoPlayback = document.getElementById("video-playback");
      videoPlayback.src = videoURL;
    };
  }
};
Kalaschnik
  • 769
  • 1
  • 7
  • 21