how i stop and exit in pure js, stream webcam in WEBRTC api js , i have in my code the following script :
<script type="text/javascript">
$(document).ready(function() {
$("#abrirModal").click(function() {
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
var constraints = {
audio: false,
video: true
};
var live = document.getElementById("live");
function successCallback(stream) {
window.stream = stream; // stream available to console
if (window.URL) {
live.src = window.URL.createObjectURL(stream);
} else {
live.src = stream;
}
$("#myModal").modal("show");
window.setTimeout(function() {
$("#myModal").modal("hide");
}, 9000);
}
function errorCallback(error) {
console.log("navigator.getUserMedia error: ", error);
}
navigator.getUserMedia(constraints, successCallback, errorCallback);
});
});
</script>
how close and exit web cam in other file.js for example:
function exitWebCam () {
document.getElementById("live")."close the web cam";
}
You end a stream by closing all of its tracks:
stream.getTracks().forEach(function(track) { track.stop(); })
What Philipp says. Also clear all references to the stream so it can be freed. Here you have a bug:
is wrong (
src
takes a URL, not a stream). Luckily it never runs sincewindow.URL
exists in all browsers that do WebRTC. ButcreateObjectURL
causes the camera to stay on. Instead do this:Or just
live.srcObject = stream
assrcObject
is implemented in all the WebRTC browsers by now (Chrome 54+). It handles resources correctly, so when you later dolive.srcObject = null
the browser knows it can garbage collect the stream (and turn off the camera should you have missed callingtrack.stop()
on any of the tracks).createObjectURL
is terrible and deprecated, and leaves resources allocated until page navigation unless you remember torevokeObjectURL
. It's why your camera never stops on its own, in case you were wondering, so if you see this pattern in code, please help stamp it out.Compare
Try these for comparison. Video disappears after 2 seconds, but keep an eye on your camera light and the in-browser recording indicator. First with
srcObject
(https fiddle for Chrome):(Cam indicator and light should go out after ~10 seconds in Firefox; ~20 seconds in Chrome.)
Then with
createObjectURL
(withoutrevokeObjectURL
) (https fiddle for Chrome):(Stays on forever in both browsers.)
track.stop()
called explicitly will stop it, but only if you've stopped all tracks, which can be easier than it sounds in general given that tracks can be cloned now. So avoidcreateObjectURL
.