WebRTC 远程和本地视频均以本地流显示

iLi*_*LiA 2 javascript webrtc

你好,我是 WebRTC 的新手,我试过这段代码

  const yourVideo = document.querySelector("#face_cam_vid");
 const theirVideo = document.querySelector("#thevid");

 (async () => {
 if (!("mediaDevices" in navigator) || !("RTCPeerConnection" in window)) {
  alert("Sorry, your browser does not support WebRTC.");
  return;
 }
  const stream = await navigator.mediaDevices.getUserMedia({video: true, 
  audio: true});
  yourVideo.srcObject = stream;

  const configuration = {
  iceServers: [{urls: "stun:stun.1.google.com:19302"}]
  };
const yours = new RTCPeerConnection(configuration);
const theirs = new RTCPeerConnection(configuration);

for (const track of stream.getTracks()) {
  yours.addTrack(track, stream);
}
theirs.ontrack = e => theirVideo.srcObject = e.streams[0];

yours.onicecandidate = e => theirs.addIceCandidate(e.candidate);
theirs.onicecandidate = e => yours.addIceCandidate(e.candidate);

const offer = await yours.createOffer();
await yours.setLocalDescription(offer);
await theirs.setRemoteDescription(offer);

const answer = await theirs.createAnswer();
await theirs.setLocalDescription(answer);
await yours.setRemoteDescription(answer);
})();
Run Code Online (Sandbox Code Playgroud)

它有效,但部分有效https://imgur.com/a/nG7Xif6。简而言之,我正在创建像在 omegle 中那样的一对一随机视频聊天,但是此代码同时显示“远程”(陌生人的)和“本地”(“我的”)视频以及我的本地流,但我想要的只是,用户等待第二个用户进行视频聊天,当第三个用户进入时应该等待第四个等等。我希望有人能帮助我

jib*_*jib 5

您将本地循环演示(您拥有的内容)与聊天室混淆了。

一个本地环路演示是短路仅客户端验证的概念,连接在同一页面上彼此两个对等连接。完全没用,除了证明 API 有效并且浏览器可以与自己对话。

它包含localPeerConnectionremotePeerConnection——或pc1pc2——并且不是人们通常编写WebRTC代码的方式。它忽略了信号。

没有服务器,信令很难演示,但我向人们展示了这个选项卡演示。右键单击并在两个相邻的窗口中打开它,然后单击Call!其中一个的按钮调用另一个。它使用localSocket,我使用 localStorage 进行信号发送的非生产黑客。

同样没用,tab-demo 看起来更像真正的代码:

const pc = new RTCPeerConnection();

call.onclick = async () => {
  video.srcObject = await navigator.mediaDevices.getUserMedia({video:true, audio:true});
  for (const track of video.srcObject.getTracks()) {
    pc.addTrack(track, video.srcObject);
  }
};

pc.ontrack = e => video.srcObject = e.streams[0];
pc.oniceconnectionstatechange = e => console.log(pc.iceConnectionState);
pc.onicecandidate = ({candidate}) => sc.send({candidate});
pc.onnegotiationneeded = async e => {
  await pc.setLocalDescription(await pc.createOffer());
  sc.send({sdp: pc.localDescription});
}

const sc = new localSocket();
sc.onmessage = async ({data: {sdp, candidate}}) => {
  if (sdp) {
    await pc.setRemoteDescription(sdp);
    if (sdp.type == "offer") {
      await pc.setLocalDescription(await pc.createAnswer());
      sc.send({sdp: pc.localDescription});
    }
  } else if (candidate) await pc.addIceCandidate(candidate);
}
Run Code Online (Sandbox Code Playgroud)

有一个——pc你的一半通话——还有一个onmessage信令回调来正确处理时间关键的非对称提供/应答协商。两边的JS一样。

这仍然不是聊天室。为此,您需要服务器逻辑来确定人们如何见面,以及用于发送信号的网络套接字服务器。在 MDN 上尝试本教程,它以聊天演示结束