You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 19:27:24