Async WebRTC replaceTrack mute
by jib1
HTML
<video id="video1" width="160" height="120" autoplay muted></video>
<video id="video2" width="160" height="120" autoplay></video><br>
<label><input type="checkbox" id="scramble">replace w/noise</label>
<button id="replacenull">replace w/null</button>
<div id="div"></div><div id="statsdiv"></div>
JavaScript
const console = {log: msg => div.innerHTML += `${msg}<br>`};
const gUM = c => navigator.mediaDevices.getUserMedia(c);
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
const pc1 = new RTCPeerConnection(), pc2 = new RTCPeerConnection();
let track;
(async () => {
try {
video1.srcObject = await gUM({video: true});
const [cameraTrack] = video1.srcObject.getVideoTracks();
const [noiseTrack] = whiteNoise().getVideoTracks();
pc1.addTrack(cameraTrack, video1.srcObject);
pc2.ontrack = e => { video2.srcObject = e.streams[0]; }
scramble.onclick = async e => {
try {
await pc1.getSenders()[0].replaceTrack(scramble.checked? noiseTrack : cameraTrack);
} catch(e) {
console.log(e);
}
}
replacenull.onclick = async e => {
try {
await pc1.getSenders()[0].replaceTrack(null);
} catch(e) {
console.log(e);
}
}
} catch (e) {
console.log(e);
}
})();
pc1.onicecandidate = e => pc2.addIceCandidate(e.candidate);
pc2.onicecandidate = e => pc1.addIceCandidate(e.candidate);
pc1.oniceconnectionstatechange = e => console.log(pc1.iceConnectionState);
pc1.onnegotiationneeded = async e => {
try {
await pc1.setLocalDescription(await pc1.createOffer());
await pc2.setRemoteDescription(pc1.localDescription);
await pc2.setLocalDescription(await pc2.createAnswer());
await pc1.setRemoteDescription(pc2.localDescription);
} catch(e) {
console.log(e);
}
}
function whiteNoise(width = 160, height = 120) {
const canvas = Object.assign(document.createElement("canvas"), {width, height});
const ctx = canvas.getContext('2d');
ctx.fillRect(0, 0, width, height);
const p = ctx.getImageData(0, 0, width, height);
requestAnimationFrame(function draw(){
for (let i = 0; i < p.data.length; i++) {
p.data[i++] = p.data[i++] = p.data[i++] = Math.random() * 255;
}
...