Article WebRTC mid correlate tracks
by jib1
HTML
<label><input type="checkbox" id="sendCamera">Send camera</label>
<label><input type="checkbox" id="sendNoise">Send white noise</label><br>
<br>Correlate tracks to always place camera on the left:<br>
<video id="videoA" width="320" height="240" autoplay></video>
<video id="videoB" width="320" height="240" autoplay></video><br>
<button onclick="camTrack.stop()">Stop Example</button><br>
<div id="div"></div>
<script src="https://jan-ivar.github.io/localloop/localloop.js"></script>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
JavaScript
let camTrack;
(async () => {
try {
const [pc1, pc2] = localPeerConnectionLoop();
camTrack = (await navigator.mediaDevices.getUserMedia({video: true})).getTracks()[0];
let camTransceiver = pc1.addTransceiver(camTrack, {direction: "inactive"});
let noiseTransceiver = pc1.addTransceiver(whiteNoise(), {direction: "inactive"});
sendCamera.onclick = () => camTransceiver.direction = sendCamera.checked ? "sendonly" : "inactive";
sendNoise.onclick = () => noiseTransceiver.direction = sendNoise.checked ? "sendonly" : "inactive";
pc2.ontrack = ({transceiver}) => {
let video = (transceiver.mid == camTransceiver.mid) ? videoA : videoB;
video.srcObject = new MediaStream([transceiver.receiver.track]);
transceiver.receiver.track.onmute = () => video.srcObject = null;
}
} catch (e) {
console.log(e)
}
})();