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
Saving a reference to the LocalMediaStream
like asgoth suggests is correct, but for me in Chrome 47. localStream.stop();
gave me an error:
Uncaught TypeError: localStream.stop is not a function
I got it to work by calling:
localStream.getVideoTracks()[0].stop();