建立第一次成功的 RTC 连接的最佳方法是什么?
以下代码有时有效,有时无效。我认为addIceCandidate
在 before 或 after 被调用是一个问题createAnswer
,我不知道哪个更可取,或者这是否是问题(为什么它不能一直工作,只需将其粘贴到浏览器中,然后尝试几次,您应该看到至少有时“呼叫”按钮并非一直有效):
<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>
请注意,有时视频流是如何稍后进来的并且是空的。