如何生成ICE候选人



我正在本地网络中使用WebRTC开发视频会议,因此我只使用一个信令服务器来交换SDP数据。据我所知,我还需要交换ICE候选人,但我不知道如何生成他们。谢谢

您可以通过设置peerConnection.onicecadidate事件来获得生成的iceCandidate。

(async () => {
const pc = new RTCPeerConnection();
pc.onicecandidate = evt => {
console.log(evt.candidate?.candidate);
};
const stream = await navigator.mediaDevices.getUserMedia({video:true});
stream.getTracks().forEach(track => pc.addTrack(track, stream));
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
})();

您是否创建了一个至少包含一个ice服务器url的配置,然后使用此配置创建RTCPeerConnection实例?设置ice服务器url时,应该触发"icecandidate"事件。

const configuration = { 
iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
};
const pc = new RTCPeerConnection(configuration);
pc.addEventListener('icecandidate', event => {
if (event.candidate) {
console.log('icecandidate received: ', event.candidate);
}
});

最新更新