RTCPeerConnection返回的localDescription缺失candidate参数求助
为什么RTCPeerConnection的localDescription里没有ICE Candidate?
你忽略了ICE候选收集的异步特性:
调用conn.setLocalDescription(offer)后,浏览器才开始后台收集ICE候选,这个过程不会被await等待完成。你当前代码里,刚执行完setLocalDescription就返回localDescription,此时ICE候选还没收集完成,自然不会出现在SDP里。
如果不想用onicecandidate回调,可以通过监听icegatheringstatechange事件,等待ICE收集状态变为complete后再返回描述,这样就能拿到包含候选的完整SDP。
修改后的代码如下:
async function getLocalDesc() { const conn = new RTCPeerConnection(); conn.createDataChannel(''); const offer = await conn.createOffer(); await conn.setLocalDescription(offer); // 等待ICE候选收集完成 await new Promise(resolve => { if (conn.iceGatheringState === 'complete') { resolve(); } else { conn.addEventListener('icegatheringstatechange', () => { if (conn.iceGatheringState === 'complete') { resolve(); } }); } }); return conn.localDescription; } (async () => { console.log(await getLocalDesc()) })();
内容的提问来源于stack exchange,提问作者A. Sinha
相关产品推荐
相关产品推荐

