Search code examples
javascriptwebrtcgetusermedia

stop the webcam streaming of getUserMedia without page refreshing


I am trying to close the webcam with javascript function (it has to be closed after receive some Ajax response), but it seems impossible to close without refreshing the page. All the methods for close it like video.src = null, video.pause...etc don't work at all in any browser. The unique way is to close the stream passed as parameter on the success functions, so there is any way to use this object outside the function success to close the webcam?

I know that this question has been asked before (Stop/Close webcam using getUserMedia and RTCPeerConnection Chrome 25), but my needs are different, so I would need some help to solve this problem

thanks!

EDIT: My working code trying to close the webcam:

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

uff..it's really complicated to post here the code XD


Solution

  • You need to stop the LocalMediaStream object by executing its stop() method. I had similar problems. What you need to do is:

    Keep a reference to the LocalMediaStream in the onSuccess callback function of the getUserMedia() execution:

    var localStream;
    
    onUserMediaSuccess = function(stream) {
       // attach to a video element
       ...
       // keep a reference
       localStream = stream;
    };
    

    Stop the LocalMediaStream where needed:

    localStream.stop(); 
    

    More info in my own question (and answer).