Search code examples
streamvideo-streamingpeerrtcpeerconnection

RTCPeerConnection replaceTrack only changing stream for the remote peer


I am new to RTCPeerConnection (WEbRTC), so please bear with me.

So far I am able to get to the point where I can replace tracks on the run by switching camera or screen sharing in my app. But I noticed it in 2 browser tabs that newly replaced track stream is captured in partner/remote peer only, not on initiator's tab. It just keep showing old stream even though stream has been replaced.

It should've been nice if initiator can also see what he/she is sharing. I tried but no luck so far. Looking for some assistance.

My code looks like:

function screenShare(){
    (async () => {
        try {
            await navigator.mediaDevices.getDisplayMedia(
                {
                    cursor: true
                }).then(stream => {
                    // localStream = stream;
                    let videoTrack = stream.getVideoTracks()[0];
                    var sender = senders.find(function(s) {
                        return s.track.kind == videoTrack.kind;
                    });
                    sender.replaceTrack(videoTrack);
                    videoTrack.onended = function(){
                        sender.replaceTrack(localStream.getTracks()[1]);
                    }
                });
        } catch (err) {
            console.log('(async () =>: ' + err);
        }
    })();
}

Thanks in advance.


Solution

  • By design replaceTrack replaces the stream on the RTCPeerConnection. This does not affect the local video object. Reset the srcObject on the local video element to change it.