replaceTrack demo
by xdumaine
HTML
<video id="v1" height="120" width="160" autoplay></video>
<video id="v2" height="120" width="160" autoplay></video><br>
<button onclick="start()">Start!</button>
<button id="flipButton" onclick="flip()" disabled>Flip!</button>
<div id="div">
JavaScript
var pc1 = new mozRTCPeerConnection(), pc2 = new mozRTCPeerConnection();
pc1.onicecandidate = e =>
!e.candidate || pc2.addIceCandidate(e.candidate).catch(failed);
pc2.onicecandidate = e =>
!e.candidate || pc1.addIceCandidate(e.candidate).catch(failed);
pc2.onaddstream = e => v2.mozSrcObject = e.stream;
var streams = [];
function start() {
navigator.mediaDevices.getUserMedia({fake:true, video:true, audio:true})
.then(stream => streams[1] = stream)
.then(() => navigator.mediaDevices.getUserMedia({video: true, audio: true}))
.then(stream => pc1.addStream(v1.mozSrcObject = streams[0] = stream))
.then(() => pc1.createOffer())
.then(offer => pc1.setLocalDescription(offer))
.then(() => pc2.setRemoteDescription(pc1.localDescription))
.then(() => pc2.createAnswer())
.then(answer => pc2.setLocalDescription(answer))
.then(() => pc1.setRemoteDescription(pc2.localDescription))
.then(() => (log("Connected!"), flipButton.disabled = false))
.catch(failed);
}
var flipped = 0;
function flip() {
flipped = 1 - flipped;
Promise.all(pc1.getSenders().map(sender =>
sender.replaceTrack((sender.track.kind == "audio")?
streams[flipped].getAudioTracks()[0] :
streams[flipped].getVideoTracks()[0])))
.then(() => log("Flip!"))
.catch(failed);
}
var log = msg => div.innerHTML += "<p>"+ msg +"</p>";
var failed = e => log(e.toString() +", line "+ e.lineNumber);