WebRTC远程和本地视频均与本地流一起显示

时间:2018-11-20 17:15:05

标签: 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);
})();

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

1 个答案:

答案 0 :(得分:3)

您将聊天室中的本地循环演示与现有的混淆。

local-loop demo是仅客户端的短路概念验证,将同一页面上的两个对等连接彼此链接。完全没用,只是证明API可以工作并且浏览器可以自言自语。

它包含localPeerConnectionremotePeerConnection(或pc1pc2),而不是通常编写WebRTC代码的方式。它省去了信令。

没有服务器就很难演示信令,但是我向人们展示了这个tab demo。右键单击并在两个相邻的窗口中打开它,然后单击一个上的Call!按钮以调用另一个。它使用localSocket,这是我使用localStorage进行信号传输所产生的非生产性入侵。

制表符演示毫无用处,看起来更像真实的代码:

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);
}

只有一个pc(占您通话的一半),并且有一个onmessage信令回调,可以正确处理对时间要求严格的非对称要约/应答协商。双方使用相同的JS。

这仍然不是聊天室。为此,您需要服务器逻辑来确定人们的见面方式,以及一个用于发出信号的Web套接字服务器。尝试以this tutorial on MDN结尾的chat demo