javascripthtmlcameragetusermedia

Stop navigator.GetUserMedia camera access


I have this camera app I'm making, and I have this camera code that starts a camera here it is.

var video = document.getElementById('video');
 // Get access to the camera
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
    video.srcObject = stream;
    video.play();
 });
}

The problem is, I am unable to stop it. So how do you stop it in javascript the navigator getUserMedia camera access?


Solution

  • Try using stream.getTracks() followed by track.stop(). For example:

    var video = document.getElementById('video');
     // Get access to the camera
    if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
        video.srcObject = stream;
        video.play();
        setTimeout(() => {
          stream.getTracks().forEach(track => {
            if (track.readyState == 'live' && track.kind === 'video') {
              track.stop();
            }
          });
        }, 5000);
      });
    }
    

    After 5 seconds, we stop the camera.

    See: Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia