reactjs - 没有 Ice Candidates 聚集,peerConnection.iceGatheringState 立即返回 "complete"

标签 reactjs firebase webrtc

我已经坚持了一段时间了。我的代码基于 https://webrtc.org/getting-started/firebase-rtc-codelab .我基本上只是将其更改为 React 和 firebase 实时数据库而不是 firestore。

const VideoRoom = () => {
  const config = {
    apiKey: xxx,
    authDomain: xxx,
    databaseURL: xxx,
    projectId: xxx,
    storageBucket: xxx,
    messagingSenderId: xxx,
    appId: xxx,
  };

  const rtcconfig = {
    iceServers: [
      {
        urls: [
          "stun:stun1.l.google.com:19302",
          "stun:stun2.l.google.com:19302",
        ],
      },
    ],
    iceCandidatePoolSize: 10,
  };

  const { roomId } = useParams();

  if (!firebase.apps.length) {
    firebase.initializeApp(config);
  }

  const db = firebase.database();
  const rooms = () => db.ref("rooms");
  const room = (roomId) => db.ref(`rooms/${roomId}`);
  const callerCandidates = (roomId) =>
    db.ref(`rooms/${roomId}/callerCandidates`);
  const calleeCandidates = (roomId) =>
    db.ref(`rooms/${roomId}/calleeCandidates`);

  const peerConnection = new RTCPeerConnection(rtcconfig);
  var localStream = new MediaStream();
  var remoteStream = null;

  var localVideo = useRef(null);
  var remoteVideo = useRef(null);

  room(roomId)
    .once("value")
    .then((snapshot) => {
      if (!snapshot.val()) {
        createRoom();
        return;
      }
      joinRoomById(roomId, snapshot.val());
    });

  useEffect(() => {
    peerConnection.addEventListener("icegatheringstatechange", () => {
      console.log(
        `ICE gathering state changed: ${peerConnection.iceGatheringState}`
      );
    });

    peerConnection.addEventListener("connectionstatechange", () => {
      console.log(`Connection state change: ${peerConnection.connectionState}`);
    });

    peerConnection.addEventListener("signalingstatechange", () => {
      console.log(`Signaling state change: ${peerConnection.signalingState}`);
    });

    peerConnection.addEventListener("iceconnectionstatechange ", () => {
      console.log(
        `ICE connection state change: ${peerConnection.iceConnectionState}`
      );
    });
  });

  const createRoom = async () => {
    console.log("create room");
    localStream.getTracks().forEach((track) => {
      console.log("adding localStream to peerConnection");
      peerConnection.addTrack(track, localStream);
    });

    peerConnection.addEventListener("icecandidate", (event) => {
      console.log("listening for icecandidate on peerConnection");
      if (!event.candidate) {
        console.log("final icecandidate");
        return;
      }
      console.log("callerCandidate written to database");
      callerCandidates(roomId).set(event.candidate.toJSON());
    });

    const offer = await peerConnection.createOffer();
    await peerConnection.setLocalDescription(offer);
    console.log("Offer created and added to peerConnection local description");

    const roomWithOffer = {
      offer: {
        type: offer.type,
        sdp: offer.sdp,
      },
    };

    await room(roomId).update(roomWithOffer);
    console.log("Offer written to room database document");

    peerConnection.addEventListener("track", (event) => {
      event.streams[0].getTracks().forEach((track) => {
        console.log(
          "listening for track on peerConnection and adding them to remoteStream"
        );
        remoteStream.addTrack(track);
      });
    });

    room(roomId).on("value", async (snapshot) => {
      console.log("listening for remote session in room database document");
      const data = snapshot.val();
      if (!peerConnection.currentRemoteDescription && data && data.answer) {
        console.log("Got remote description: ", data.answer);
        const rtcSessionDescription = new RTCSessionDescription(data.answer);
        await peerConnection.setRemoteDescription(rtcSessionDescription);
      }
    });

    calleeCandidates(roomId).on("value", (snapshot) => {
      console.log(
        "listening for remote ICE candidates in room/calleCandidates database document"
      );
      if (snapshot.val()) {
        snapshot.val().forEach(async (change) => {
          if (change.type === "added") {
            let data = change.doc.data();
            await peerConnection.addIceCandidate(new RTCIceCandidate(data));
          }
        });
      }
    });
  };
};

我通过 React 路由器获取 roomId,为了可读性,我省略了组件的其余部分。

控制台返回如下:

创建房间
信号状态变化:have-local-offer
优惠已创建并添加到 peerConnection 本地描述
ICE 收集状态更改:完成
在 peerConnection 上监听 icecandidate
最终冰候选人
将 localStream 添加到 peerConnection
报价写入房间数据库文件
在 room/calleCandidates 数据库文件中监听远程 ICE 候选人
在房间数据库文件中监听远程 session

在 about:webrtc firefox 选项卡中,我可以看到报价已成功创建,但没有任何 ice 候选人

提前致谢!

最佳答案

因此,事实证明,ICE 候选人收集仅在将某些轨道添加到流中时才开始,并且必须在创建报价之前完成。

因此,如果您在创建报价之前收集媒体并将其添加到 RTCPeerConnection 实例,那么您将看到正确收集 ICE 候选人。

编辑:除此之外,如果您在创建报价时提供如下选项,它将按预期开始 ICE 收集:

await this.connection.createOffer({
  offerToReceiveAudio: true,
  offerToReceiveVideo: true,
});

希望对您有所帮助!

关于reactjs - 没有 Ice Candidates 聚集,peerConnection.iceGatheringState 立即返回 "complete",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61325035/

相关文章:

javascript - 在 React.js 中设置和重置状态

android - 模拟 FirebaseRemoteConfig getBoolean()

javascript - 如何使 this 引用函数中的类?

javascript - 使用 django channel 将 webRTC 视频流发送到服务器

javascript - JSSIP WebRTC 手机 30 秒后自动断开连接

javascript - 如何使用 React 显示工作中的数字时钟

javascript - 如何在导航到 React 'page' 后运行 JavaScript 函数

javascript - 使用 componentWillRecieveProps 从 App.js 接收 Prop

java - 收到 fcm 通知时更新回收器 View

javascript - 当 Firebase 数据不是 "undefined"时