rtcpeerconnection 跟踪事件有时会返回空流

rtcpeerconnection track event sometimes returning empty stream

设置首次成功的 RTC 连接的最佳方法是什么?

以下代码有时有效,有时无效。我认为 addIceCandidatecreateAnswer 之前或之后被调用是一个问题,我不知道哪个更可取,或者这是否是问题所在(为什么它不能一直工作,只需将其粘贴到浏览器中,然后尝试几次,您应该会发现至少有时 "call" 按钮不会一直工作):

<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>

请注意,有时视频流会延迟出现且为空。

look again at documentation。起初,您使用的是异步函数,因此在您调用它时无法解析(例如,用户不回答提示或浏览器根本拒绝它)。其次,您没有处理错误,将 catch() 块添加到您的代码中,浏览器将自己回答您的问题

我运行以前用PeerConnectionAPI遇到同样的问题,问题是Unified Plan SDP格式,也许值得一读。