停止getUserMedia的网络摄像头流媒体,无需刷新页面

use*_*954 15 javascript webrtc getusermedia

我试图用javascript函数关闭网络摄像头(它必须在收到一些Ajax响应后关闭),但似乎无法关闭而不刷新页面.关闭它的所有方法,如video.src = null,video.pause ...等在任何浏览器中根本不起作用.唯一的方法是关闭在成功函数上作为参数传递的流,所以有什么方法可以在函数成功之外使用这个对象来关闭网络摄像头?

我知道之前已经问过这个问题(使用getUserMedia和RTCPeerConnection Chrome 25停止/关闭网络摄像头),但我的需求不同,所以我需要一些帮助来解决这个问题

谢谢!

编辑:我的工作代码试图关闭网络摄像头:

navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia ||  navigator.webkitGetUserMedia || navigator.msGetUserMedia;
if(navigator.getUserMedia){
  var video_constraints = {
    mandatory: {
       maxHeight: 480,
       maxWidth: 640 
    },
    optional: []
  };
  var self = this;
  self.navigator.getUserMedia({
      audio: false,
      video: video_constraints
  }, self.onSuccess, onError);
}
else{
  alert('An error has occurred starting the webcam stream, please revise the instructions to fix the problem');
}

function onSuccess(stream) {
  var video = document.getElementById('webcam');

  if(navigator.webkitGetUserMedia || navigator.mozGetUserMedia){
      video.src = window.URL.createObjectURL(stream);
  }
  else if(navigator.msGetUserMedia){
      //future implementation over internet explorer
  }
  else{
      video.src = stream;
  }
  self.localStream = stream;
  video.play();
}
function onError() {
  alert('There has been a problem retrieving the streams - did you allow access?');
}

function closeWebcamConnection(){
  this.localStream.stop();
}
Run Code Online (Sandbox Code Playgroud)

uff ..在这里发布代码XD真的很复杂

Jay*_* P. 47

保存对LocalMediaStream类似的引用似乎是正确的,但对于我在Chrome 47. localStream.stop();给了我一个错误:

Uncaught TypeError: localStream.stop is not a function
Run Code Online (Sandbox Code Playgroud)

我打电话给它工作:

localStream.getVideoTracks()[0].stop();
Run Code Online (Sandbox Code Playgroud)

  • 目前(截至2015年12月)这是一个重要的答案.我们在网络应用中遇到此问题,导致Chrome中的标签因"Aw,snap"消息而崩溃.这解决了我们的问题. (6认同)

asg*_*oth 29

您需要LocalMediaStream通过执行其stop()方法来停止对象.我有类似的问题.你需要做的是:

保持LocalMediaStreamgetUserMedia()执行的onSuccess回调函数的引用:

var localStream;

onUserMediaSuccess = function(stream) {
   // attach to a video element
   ...
   // keep a reference
   localStream = stream;
};
Run Code Online (Sandbox Code Playgroud)

在需要的地方停止LocalMediaStream:

localStream.stop(); 
Run Code Online (Sandbox Code Playgroud)

更多信息在我自己的问题(和答案).

  • 不再起作用了:https://developer.mozilla.org/en-US/docs/Web/API/MediaStream (3认同)

Pet*_*ols 9

除了asgoth的答案

Chrome 45中已弃用localStream.stop(),已在Chrome 47中删除

如果你从多个地方调用.stop(),你可以使用以下帮助程序来使用stop函数将逻辑保存在一个地方.

var localStream;

onUserMediaSuccess = function(stream) {

  // re-add the stop function
  if(!stream.stop && stream.getTracks) {
    stream.stop = function(){         
      this.getTracks().forEach(function (track) {
         track.stop();
      });
    };
  }

  // attach to a video element
  ...
  // keep a reference
  localStream = stream;
};
Run Code Online (Sandbox Code Playgroud)