Async trackless replaceTrack
by jib1
HTML
<video id="video" width="160" height="120" autoplay></video><br>
<div id="div"></div>
JavaScript
const console = { log: msg => div.innerHTML += msg + "<br>" };
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
const pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();
(async () => {
try {
pc1.addTransceiver("audio");
const tc1 = pc1.addTransceiver("video");
const stream = await navigator.mediaDevices.getUserMedia({video: true});
const [track] = stream.getVideoTracks();
await pc1.setLocalDescription();
await pc2.setRemoteDescription(pc1.localDescription);
await pc2.setLocalDescription();
await pc1.setRemoteDescription(pc2.localDescription);
await wait(2000);
await tc1.sender.replaceTrack(track);
} catch (e) {
console.log(e);
}
})();
pc1.onicecandidate = e => pc2.addIceCandidate(e.candidate);
pc2.onicecandidate = e => pc1.addIceCandidate(e.candidate);
pc1.oniceconnectionstatechange = () => console.log(pc1.iceConnectionState);
pc2.ontrack = ({track}) => video.srcObject = new MediaStream([track]);
function snowBoarder(width = 160, fillStyle = '#eeeeee', font = "120px Arial", a = 0) {
const can = Object.assign(document.createElement("canvas"), {width, height: width});
const c = Object.assign(can.getContext('2d'), {fillStyle, font});
const rotate = (a, o) => (c.translate(o, o), c.rotate(a), c.translate(-o, -o));
requestAnimationFrame(function draw(){
c.fillRect(0, 0, width, width);
rotate(a += Math.PI / 90 * (8 + 7*Math.cos(3*Math.PI + a/10)), width/2);
c.fillText("🏂", width/2 - 14*width/32, width/2 + 10*width/32);
rotate(-a, width/2);
requestAnimationFrame(draw);
});
return can.captureStream(60).getTracks()[0];
};