WebRTC视频未显示 [英] WebRTC video is not displaying

查看:360
本文介绍了WebRTC视频未显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一对一的webrtc视频聊天室,此代码不起作用,我想知道为什么

i am creating one-to-one webrtc video chatroom and this code does not working and i wanna know why

function hasUserMedia(){
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
return !!navigator.getUserMedia; 
}

function hasRTCPeerConnection() {
window.RTCPeerConnection = window.RTCPeerConnection || 
window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
return !!window.RTCPeerConnection;
}



 function startPeerConnection(stream) {
 var configuration = {

    "iceServers": [{ "url": "stun:stun.1.google.com:19302" }]
 };
 yourConnection = new RTCPeerConnection(configuration);
 theirConnection = new webkitRTCPeerConnection(configuration);

 yourConnection.addStream(stream);
 theirConnection.onaddstream = function (e) {
     theirVideo.src = window.URL.createObjectURL(e.stream);
 };


 yourConnection.onicecandidate = function (event) {
    if (event.candidate){

   theirConnection.addIceCandidate(newRTCIceCandidate(event.candidate));
    }
  };

 theirConnection.onicecandidate = function (event) {
    if (event.candidate) {
        yourConnection.addIceCandidate(new 
  RTCIceCandidate(event.candidate));
    }
  };

    yourConnection.createOffer(function (offer) {
    yourConnection.setLocalDescription(offer);
    theirConnection.setRemoteDescription(offer);

    theirConnection.createAnswer(function (offer) {
        theirConnection.setLocalDescription(offer);
        yourConnection.setRemoteDescription(offer);
    });
    });
     }


    var yourVideo = document.querySelector("#face_cam_vid"),
    theirVideo = document.querySelector("#thevid"),
   yourConnection, theirConnection;

   if (hasUserMedia()) {
      navigator.getUserMedia({ video: true, audio: true }, function(stream) 
 {
        yourVideo.src = window.URL.createObjectURL(stream);
        if (hasRTCPeerConnection()) {
            startPeerConnection(stream);
        } else {
            alert("Sorry, your browser does not support WebRTC.");
        }
         }, function (error) {
         console.log(error);
        }
               );
     } else {
      alert("Sorry, your browser does not support WebRTC.");
    }

并且此代码给了我这样的错误错误,如您所见视频未显示,我试图创建div(其中有视频标签),但还是无法正常工作

and this code is giving me a errors like thiserrors and as u see video is not displaying , i tried to create div (where video tag is) but it did not work anyway

如果您能帮助我,我会很高兴这里是我的html

if u can help my i will be glad here is my html

 <!DOCTYPE html>
 <html>

 <head>
 <title>
  Video Call
 </title>
 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" type="text/css" media="screen" href="vidd.css" />
 <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
 <script src="/videof.js"></script>

 <script>var width = Math.max(window.screen.width, window.innerWidth);

    if(width <= 414){
        var faceCam = document.getElementById("face_cam");
        faceCam.style.width = "15%";
    }

    function smaller(){
        if(width <= 414){
            var size = document.getElementById("face_cam").style.width;
            if(size == "15%"){
                faceCam.style.width = "3%";
                faceCam.style.height = "3%";
                faceCam.style.borderRadius = "0px"
            }
            else if(size == "3%"){
                faceCam.style.width = "15%";
                faceCam.style.height = "30%";
                faceCam.style.borderRadius = "10px"
            }
        }

        else{
            var size = document.getElementById("face_cam").style.width;
            if(size == "30%"){
                faceCam.style.width = "3%";
                faceCam.style.height = "3%";
                faceCam.style.borderRadius = "0px"
            }
            else if(size == "3%"){
                faceCam.style.width = "30%";
                faceCam.style.height = "30%";
                faceCam.style.borderRadius = "10px";
            }
         }
        }


     var width = Math.max(window.screen.width, window.innerWidth);

     function smaller(){
        var size = document.getElementById("face_cam").style.height;
        if (size == "30%"){
            var frame = document.getElementById("face_cam");
            frame.style.height = "3%";
            frame.style.width = "4%";
            frame.borderRadius = "0px";
        }

        else{
            var frame = document.getElementById("face_cam");
            frame.style.height = "30%";
            frame.style.width = "30%";
        }
        }
         function BACKT(){ 
              window.location.href = "http://localhost:8000/"
        }

       </script>
       </head>

       <body>
      <div class="test_vc_field">
      <video id="thevid" autoplay></video>
     <div id="face_cam" onclick="smaller()" style="height: 30%; width: 30%">
     <video id="face_cam_vid" autoplay></video>
    </div>
    </div>
    <div class="nav">
   <button class="next">შემდეგი</button>
   <img src="next.png" class="next_icon">
    <button class="off" id="off">გათიშვა</button>
   <img src="shutdown.png" class="shd_icon">
  <button class="goto_main" id="WTfu" onclick="BACKT();">მთავარი 
  გვერდი</button>
  <img src="home.png" class="home_icon" onclick="main()">
  </div>
  </body>

   </html>

第二个用户显示face_cam_vid的#thevid id vid是我显示的视频

#thevid id vid where second user displays face_cam_vid is video where i display

推荐答案

这是过时的代码.它包含6个跟踪WebRTC API演变的问题.

It's outdated code. It contains 6 problems that track the evolution of the WebRTC API.

TL; DR:,该操作不起作用,因为您没有检查错误,并且只测试了一种浏览器.

TL;DR: It doesn't work because you're not checking for errors and you've only tested one browser.

yourConnection = new RTCPeerConnection(configuration);
theirConnection = new webkitRTCPeerConnection(configuration); // <-- wrong

webkit-名称在Firefox或Edge中不起作用.这些年来已经不需要了.如果您切换到navigator.mediaDevices.getUserMedia,则可以完全跳过10行前缀修饰前导.

webkit-names won't work in Firefox or Edge. These haven't been needed in years. Provided you switch to navigator.mediaDevices.getUserMedia, you can skip your 10 lines of prefix-mangling preamble entirely.

从技术上讲这是错误的,尽管我怀疑大多数浏览器都允许它:

This is technically wrong, though I suspect most browsers allow it:

iceServers: [{url: "stun:stun.1.google.com:19302"}] // <-- wrong

代替使用:

iceServers: [{urls: "stun:stun.1.google.com:19302"}]

...因为从技术上来说,可以通过多个网址访问ICE服务器.

...because an ICE server may technically be reachable at multiple urls.

这是错误的:

navigator.getUserMedia({video: true, audio: true}, function(stream) { /* ... */ });

...因为第三次失败回调参数是必需的. Edge说TypeError: Argument not optional.

...because a 3rd failure callback argument is required. Edge says TypeError: Argument not optional.

Chrome和Safari中的旧版错误允许这样做,但在Firefox或Edge中将无法使用.忽略错误会使您无法了解为什么事情行不通.如果用户拒绝摄像头访问,您想知道.

Legacy bugs in Chrome and Safari allow this, but it won't work in Firefox or Edge. Ignoring errors deprives you of learning why things don't work. If the user denies camera access, you wanna know.

所有现代浏览器均支持承诺 mediaDevices上的href ="https://w3c.github.io/mediacapture-main/getusermedia.html#idl-def-mediadevices-partial-1" rel ="noreferrer"> API版本.改用它:

All modern browsers support the promise version of the API on mediaDevices. Use that instead:

navigator.mediaDevices.getUserMedia({video: true, audio: true})
  .then(stream => { /* use stream here */ })
  .catch(error => console.log(error));

4)您陷入了RTCPeerConnection的承诺/回调混合陷阱":

我已经回答了,但总之,这与上面的#2类似,但有所不同.这是错误的:

4) You fell in RTCPeerConnection's "promise/callback mix-up trap":

I've answered this before, but in short, this is similar to #2 above, but with a twist. This is wrong:

yourConnection.createOffer(function(offer) { /* ... */ }); 

您认为您正在调用旧的回调API ,但是你不是.那些需要 两个 参数:

You think you're calling the old callback API, but you're not. Those required two arguments:

yourConnection.createOffer(successCallback, failureCallback /*, optionsObject */);

实际上,您实际上是在调用同名的现代的Promise API ,因为函数是JS中的对象:

Instead, you're actually calling the same-named modern promise API, because a function is an object in JS:

const promise = yourConnection.createOffer(optionsObject);

这是您的代码停止工作的地方.永远不会调用您的回调函数,而是将其解释为空的选项对象.您忽略返回的承诺.请改用Promise API.

This is where your code stops working. Your callback function is never called, being interpreted as an empty options object instead. You ignore the returned promise. Use the promise API instead.

它已在Firefox和Chrome 71中删除(收到的警告).这是错误的:

It was removed in Firefox and Chrome 71 (the warning you received). This is wrong:

theirVideo.src = URL.createObjectURL(stream);

请改用此:

theirVideo.srcObject = stream;

6)为了加分:不推荐使用整个流API(使用轨道).

addStream()& onaddstream不再存在于规范中,并且只能在某些浏览器中使用:

6) For extra points: The whole stream API is deprecated (use tracks).

addStream() & onaddstream are no longer in the spec, and only work in some browsers:

yourConnection.addStream(stream);
theirConnection.onaddstream = e => theirVideo.srcObject = e.stream;

相反,对等连接现在完全基于轨道.改用它:

Instead, peer connections are now entirely track-based. Use this instead:

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

有关这些差异的更多信息,请参见我的博客.

For more on these differences, see my blog.

以下在所有浏览器中均应工作:

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

这篇关于WebRTC视频未显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆