JSFiddle - React, Tailwind, and code Playground
HTML
<audio id="audioPlayer" autoplay controls></audio>
JavaScript
// Can we get media before applying remote answer?
localStream = undefined;
addingAudio = false;
pc1Connected = false;
pc2Connected = false;
pc1 = new RTCPeerConnection();
pc2 = new RTCPeerConnection();
pc1.ontrack = _ => console.log("ontrack 1");
pc1.onicecandidate = e => pc2.addIceCandidate(e.candidate);
pc1.oniceconnectionstatechange = e => {
console.log("iceconnectionstatechange 1: " + pc1.iceConnectionState);
if (pc1.iceConnectionState == "connected") {
pc1Connected = true;
}
if (pc1Connected == true && pc2Connected == true) {
console.log("Both sides are connected, offer to receive audio on pc1.")
addingAudio = true;
tr = pc1.addTransceiver("audio");
audioPlayer = document.getElementById("audioPlayer");
audioPlayer.srcObject = new MediaStream([tr.receiver.track]);
tr.receiver.track.onmute = _ => console.log("pc1 track onmute");
tr.receiver.track.onunmute = _ => console.log("pc1 track onunmute");
}
}
pc2.onicecandidate = e => pc1.addIceCandidate(e.candidate);
pc2.oniceconnectionstatechange = e => {
console.log("iceconnectionstatechange 2: " + pc2.iceConnectionState);
if (pc2.iceConnectionState == "connected") {
pc2Connected = true;
}
if (pc1Connected == true && pc2Connected == true) {
addingAudio = true;
console.log("Both sides are connected, offer to receive audio on pc1.")
pc1.addTransceiver("audio");
}
}
pc1.onnegotiationneeded = async _ => {
console.log("onnegotiationneeded 1");
offer = await pc1.createOffer();
await pc1.setLocalDescription(offer);
await pc2.setRemoteDescription(offer);
if (addingAudio == true) {
pc2.addTrack(localStream.getTracks()[0]);
answer = await pc2.createAnswer();
await pc2.setLocalDescription(answer);
// await pc1.setRemoteDescription(answer);
} else {
answer = await pc2.createAnswer();
await...