How to do screen sharing with simple-peer webRTC SDK

2.5k views Asked by At

I'm trying to implement webrtc & simple peer to my chat. Everything works but I would like to add screen sharing option. For that I tried that:

$("#callScreenShare").click(async function(){
   if(captureStream != null){                
     p.removeStream(captureStream)
     p.addStream(videoStream)
     captureStreamTrack.stop()
     captureStreamTrack =captureStream= null
     $("#callVideo")[0].srcObject = videoStream
     $(this).text("screen_share")
   }else{
     captureStream = await navigator.mediaDevices.getDisplayMedia({video:true, audio:true})
     captureStreamTrack = captureStream.getTracks()[0]
     $("#callVideo")[0].srcObject = captureStream
     p.removeStream(videoStream)
     console.log(p)
     p.addStream(captureStream)
     $(this).text("stop_screen_share")
   }
})

But I stop the camera and after that doesn't do anything and my video stream on my peer's computer is blocked. No errors, nothing only that.

I've put a console.log when the event stream is fired. The first time it fires but when I call the addStream method, it doesn't

If someone could help me it would be really helpful.

2

There are 2 answers

0
JOEL EYONG On

The below function will do the trick. Simply call the replaceTrack function, passing it the new track and the remote peer instance.

function replaceTrack(stream, recipientPeer ) {
  recipientPeer.replaceTrack(
    recipientPeer.streams[0].getVideoTracks()[0],
    stream,
    recipientPeer.streams[0]
  )
}
2
Dirk V On

What I do is replacing the track. So instead of removing and adding the stream:

p.streams[0].getVideoTracks()[0].stop()
p.streams[0].replaceTrack(p.streams[0].getVideoTracks()[0], captureStreamTrack, p.streams[0])

This will replace the video track from the stream with the one of the display.

simple-peer docs