html5 getUserMedia Api停止摄像头按钮不起作用

时间:2015-08-04 01:30:35

标签: javascript html5 api getusermedia

我正在localhost XAMPP服务器上执行此代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<video onclick="changeFilter(this);"width=200 height=200 id="video" controls autoplay></video> 
<p>
<button onclick="startWebcam();">Start WebCam</button>
<button onclick="stopWebcam();">Stop WebCam</button> 
</p>
 <script>
 navigator.getUserMedia = ( navigator.getUserMedia ||
                   navigator.webkitGetUserMedia ||
                   navigator.mozGetUserMedia ||
                   navigator.msGetUserMedia);

 var webcamStream;

 function startWebcam() {
 if (navigator.getUserMedia) {
 console.log("toto");
 navigator.getUserMedia (

    // constraints
    {
      video: true,
      audio: false
    },

    // successCallback
     function(localMediaStream) {
      var video = document.querySelector('video');
      video.src = window.URL.createObjectURL(localMediaStream);
      webcamStream = localMediaStream;
    },

    // errorCallback
       function(err) {
       console.log("The following error occured: " + err);
       }
     );
    } else {
    console.log("getUserMedia not supported");
      }  
     }

  function stopWebcam() {
  localMediaStream.stop();
  }
</script>
</body>
</html>

此代码启动我的网络摄像头,但是当我按下Stop WebCam按钮时,控制台会出现以下错误:

Uncaught TypeError: Cannot read property 'stop' of undefined function stopWebcam() { webcamStream.stop(); }

我是一名JavaScript新手,我在这里看不到问题。

1 个答案:

答案 0 :(得分:1)

在stopWebcam()中无法使用

localMediaStream。有关What is the scope of variables in JavaScript?

的更多信息,请参阅此帖子

...试

  function stopWebcam() {
      webcamStream.stop();
  }