How to switch between webcam and screen share using a single WebRTC live stream?

You can use replaceTrack for this.

So you create a track for the screen with getDisplayMedia, and one for the camera with getUserMedia and you store the streams in two variables, let’s say ‘camera’ and ‘screen’. So you store the stream variable you get through both methods.

Then, to switch in this example from ‘camera’ to ‘stream’, :

     peerConnection.getSenders().forEach(
      function (rtpSender) {
        if (rtpSender.track.kind == 'video') {
          rtpSender.replaceTrack(screen.getVideoTracks()[0]).then(function() {
            console.log("Replaced video track from camera to screen");
          }).catch(function(error) {
            console.log("Could not replace video track: " + error);
          });
        }
      }
     );
1 Like