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:
- append additional streams
- remove existing streams
- 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:
- don't exchange ICE, or
- don't use
DtlsSrtpKeyAgreement
(remember, for chrome 30 and earlier releases only)
// 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.