rtcpeerconnection track event sometimes returning empty stream

Viewed 1308

What is the best approach for setting up an RTC connection that will success the first time ?

The following code sometimes works, sometimes doesn't. I think it's a problem with addIceCandidate being called either before or after createAnswer, and I don't know which is preferable, or if that is even the issue (for why its not working all the time, just paste it into a browser, and try it a few times, you should see that at least sometimes the "call" button doesn't work all the time):

<body>
    <style>
        video {
            width: 300px
        }
    </style>
    <button id="s">start</button>
    <button id=c>Call</button><br>
<video id="L" autoplay muted></video>
<video id=R autoplay></video>
<video id=R2 autoplay></video>
<video id=R3 autoplay></video>
<script>
var ls, p, p2, bpl, bpr, con = {
 //   sdpSemantics: "default"
}, deets = {
    offerToReceiveAudio: 1,
    offerToReceiveVideo: 1
}

function g() {
    navigator.
    mediaDevices.getDisplayMedia().then(s => {
        ls = L.srcObject = s;

    })
}
s.onclick = e => {
    g()
};

function wow(data={}) {
    let local  = new RTCPeerConnection(con),
        remote = new RTCPeerConnection(con);

    local .addEventListener("icecandidate", e => oic(remote, e));
    remote.addEventListener("icecandidate", e => oic(local , e));

    remote.addEventListener("track", e => grs(data.video, e));

    data
        .localStream
        .getTracks()
        .forEach(t => {
            local.addTrack(t, data.localStream);
        });

    local.createOffer(deets).then(offer => {
        local .setLocalDescription(offer);
        remote.setRemoteDescription(offer);

        remote.createAnswer().then(answer => {
            remote.setLocalDescription(answer);
            local .setRemoteDescription(answer);
        })
    });
}

c.onclick = e => {
    let localStream = ls;
    wow({
        video: R,
        localStream
    });

    wow({
        video: R2,
        localStream
    });

    wow({
        video: R3,
        localStream
    });

};

function grs(vid,e) { 
    if(vid.srcObject !== e.streams[0]) {
        vid.srcObject = e.streams[0];
    }
}

function oic(pc, e) {
    let other = pc;
    if(e.candidate)
        other
        .addIceCandidate(e.candidate)
}
</script>
</video>
</body>

Notice how sometimes the video streams come in later and empty.

2 Answers

Please look again at documentation. At first, you are using async functions, so it could not resolve at the time then you call it (for example user doesn't answer for prompt or browser decline it at all). At second, you're not handling errors, add catch() block to your code and browser will answer to your question itself

Related