How to (stop, exit) video in webrtc user media browser

as I stop and exit in pure js, a streaming webcam in WEBRTC api js, I have the following script in my code:

<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 to close and exit the webcam in other .js files, for example:

  function exitWebCam () {  
     document.getElementById("live")."close the web cam";
  }
+5
source share
2 answers

You end the stream by closing all its tracks: stream.getTracks().forEach(function(track) { track.stop(); })

+2
source

What Philip says. Also clear all links to the stream so that it can be freed. Here you have an error:

live.src = stream;

(src URL-, ). , , window.URL , WebRTC. createObjectURL . :

if (typeof live.srcObject == "object") {
    live.srcObject = stream;
} else {
    live.src = window.URL.createObjectURL(stream)
}

live.srcObject = stream, srcObject WebRTC (Chrome 54+). , , live.srcObject = null, , ( , track.stop() ).

createObjectURL , revokeObjectURL. , , , , , , .

. 2 , . srcObject (https Chrome):

( Cam ~ 10 Firefox, ~ 20 Chrome.)

var wait = ms => new Promise(resolve => setTimeout(resolve, ms));

navigator.mediaDevices.getUserMedia({video: true})
  .then(stream => video.srcObject = stream)
  .then(() => wait(2000))
  .then(() => video.srcObject = null)
  .catch(e => console.log(e.name + ": "+ e.message));
<video id="video" width="160" height="120" autoplay></video>
Hide result

createObjectURL ( revokeObjectURL) (https Chrome):

( .)

var wait = ms => new Promise(resolve => setTimeout(resolve, ms));

navigator.mediaDevices.getUserMedia({video: true})
  .then(stream => video.src = URL.createObjectURL(stream))
  .then(() => wait(2000))
  .then(() => video.srcObject = null)
  .catch(e => console.log(e.name + ": "+ e.message));
<video id="video" width="160" height="120" autoplay></video>
Hide result

track.stop(), , , , , , , . createObjectURL.

+4

All Articles