如何使用WebRTC开始视频流?

3
我正在编写以下代码,以使用webRTC技术在Google Chrome浏览器上启动我的摄像头并观看我的视频。我创建了两个文件index.html和client.js。我已经附上了两者的代码。Node.js服务器已安装在我的PC上。问题是我的相机正在开启,但我无法看到视频流。 client.js代码:
function hasUserMedia() { 
   //check if the browser supports the WebRTC 
   return !!(navigator.getUserMedia || navigator.webkitGetUserMedia || 
      navigator.mozGetUserMedia); 
} 

if (hasUserMedia()) { 
   navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia
      || navigator.mozGetUserMedia; 

   //enabling video and audio channels 
   navigator.getUserMedia({ video: true, audio: true }, function (stream) { 
      var video = document.querySelector('video'); 

      //inserting our stream to the video tag     
      video.src = window.URL.createObjectURL(stream); 
   }, function (err) {}); 
} else { 
   alert("WebRTC is not supported"); 
}`

index.html

<!DOCTYPE html> 
<html lang = "en">

   <head> 
      <meta charset = "utf-8" /> 
       <link rel="stylesheet" href="css/main.css" />
   </head> 

   <body> 
      <video autoplay></video>
      <script src = "js/client.js"></script>     
   </body>
    </html>

Chrome需要https。不过在Firefox中应该可以工作。此外,正如答案提到的那样,您复制了一些非常古老的代码。 - jib
1个回答

3

看起来你正在使用旧代码,现在 API 已经改变,最好开始使用最新的 API。

请参见 演示源代码

在你的 client.js 中尝试以下代码片段:

var constraints =  { audio: true,  video: true};
navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
   var video = document.querySelector('video');
   video.srcObject = stream;
}).catch(function(err) {
     console.log('Error in getting stream', err);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接