0

我正在尝试通过 WebRTC 在两个客户端之间建立对等连接,然后通过连接从摄像头传输视频。问题是,虽然我可以清楚地看到remotePc.ontrack事件被触发,但远程端没有显示视频。也没有抛出错误。我不想使用 icecandidates 机制(并且不应该需要它),因为结果应用程序只会在本地网络上使用(信令服务器只会为客户端交换 SDP)。为什么我的示例不起作用?

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Title</title>
  </head>
  <body>
    <video id="local" autoplay playsinline></video>
    <video id="remote" autoplay playsinline></video>
    <script>
      const localVideoElem = document.getElementById("local");
      const remoteVideoElem = document.getElementById("remote");

      const localPc = new RTCPeerConnection();
      const remotePc = new RTCPeerConnection();
      remotePc.ontrack = (event) => {
        remoteVideoElem.srcObject = event.streams[0];
      };

      navigator.mediaDevices
        .getUserMedia({
          video: true,
          audio: false,
        })
        .then((stream) => {
          localVideoElem.srcObject = stream;
          stream
            .getTracks()
            .forEach((track) => localPc.addTrack(track, stream));
          return localPc.createOffer({
            offerToReceiveVideo: true,
            offerToReceiveAudio: false,
          });
        })
        .then((offer) => {
          localPc.setLocalDescription(offer);
          remotePc
            .setRemoteDescription(offer)
            .then(() => remotePc.createAnswer())
            .then((answer) => {
              remotePc.setLocalDescription(answer).then(() => {
                localPc.setRemoteDescription(answer).then(() => {
                  console.log(localPc);
                  console.log(remotePc);
                });
              });
            });
        });
    </script>
  </body>
</html>
4

1 回答 1

1

需要ICE 候选人,因为他们会告诉您客户端将相互连接的本地地址。

不过,您不需要 STUN 服务器。

于 2021-06-06T16:49:51.537 回答