WebRTC - Restart Video Stream After Calling stop()

Viewed 1247

So, I am using webRTC to create a local stream (video and audio), and want to be able to stop and restart the video of said stream.

At the point where I want to stop the stream I am getting the local video track:

     var vidTrack = this.videoEl.srcObject.getTracks().find(track => track.kind == 'video')

I then call stop() on the track, which works, and turns off the camera-light indicator on my device (which is what I want). The problem is this seems to be a one way method, there is no way to restart the stream once I call stop() on it.

I have played with just toggling the enabled boolean on the track object, which DOES disable the track from coming through, but does NOT stop displaying the camera-light indicator on my device (which I need, and stop() does).

Just wondering if anyone has come across this issue/has ideas or solutions as to get what I need.

2 Answers

Here is the solution I ended up with for anyone who may see this in the future, based on Dirk V's response:

  if (vidTrack && toggle && vidTrack.readyState && vidTrack.readyState == "ended") {
    let newVideoStreamGrab = await navigator.mediaDevices.getUserMedia({
      video: true
    })
    this.stream.removeTrack(this.stream.getVideoTracks()[0])
    this.stream.addTrack(newVideoStreamGrab.getVideoTracks()[0])
  } else {
    vidTrack.stop()
  }

The best way is to request the stream from the camera again after stopping it as there is no way to restart the stopped track.

The enabled flag is only used to allow or disallow the track to render frames. So this means that it doesn't affect the state of the camera.

When true, enabled indicates that the track is permitted to render its actual media to the output. When enabled is set to false, the track only generates empty frames. source

Related