How to switch streams? / Demo

HOME © Muaz Khan . @WebRTCWeb . Github . Latest issues . What's New?

Renegotiate to switch streams

Renegotiation is a process allows you modify pre-created peer connections when you want to:

  1. append additional streams
  2. remove existing streams
  3. modify SDP for peers direction or something else

Renegotiation means re-exchanging offer/answer SDP among peers.

On chrome, out of a known bug, when renegotiating; either:

  1. don't exchange ICE, or
  2. don't use DtlsSrtpKeyAgreement (remember, for chrome 30 and earlier releases only)
Remember, now DTLS/SRTP doesn't need to be disabled for renegotiation. It was just a workaround for chrome older builds.
// 1st solution
peer.onicecandidate = function() {
    // if you already set OfferToReceiveAudio:true and OfferToReceiveVideo:true
    if(renegotiating) return;
    
    // otherwise, you MUST NOT use {if-block} here
    // {if-block} means don't add new candidates; also, don't share
};

// or 2nd solution
var peerConnection = new RTCPeerConnection(IceServers, null);

Remember, renegotiation means: use existing peer connections to negotiate session descriptions.

Example:

Assuming that you've an existing peer connection between two users. To switch stream from audio to video; and renegotiate from offerer's side:

offerer.removeStream(audioStream);
offerer.addStream(videoStream);

offerer.createOffer(function(offerSDP) {
    socket.send({
        targetUser: 'B',
        sdp: offerSDP
    })
}, failureCallback, sdpConstraints);

Renegotiate from answerer's side; and switch from audio to video:

answerer.removeStream(audioStream);
answerer.addStream(videoStream);

answerer.setRemoteDescription(new RTCSessionDescription(socket.offerSDP));
answerer.createAnswer(function(answerSDP) {
    socket.send({
        targetUser: 'A',
        sdp: answerSDP
    })
}, failureCallback, sdpConstraints);

For a reusable function; a simple trick could be:

var peerConnection;

if(renegotiate == false) {
   peerConnection = new RTCPeerConnection(IceServers, null);
}

Try a demo.



Feedback

Enter your email too; if you want "direct" reply!