[javascript] Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

I opened a webcam by using the following JavaScript code:

const stream = await navigator.mediaDevices.getUserMedia({ /* ... */ });

Is there any JavaScript code to stop or close the webcam? Thanks everyone.

This question is related to javascript html html5-video webrtc getusermedia

The answer is


If the .stop() is deprecated then I don't think we should re-add it like @MuazKhan dose. It's a reason as to why things get deprecated and should not be used anymore. Just create a helper function instead... Here is a more es6 version

function stopStream (stream) {
    for (let track of stream.getTracks()) { 
        track.stop()
    }
}

Try method below:

var mediaStream = null;
    navigator.getUserMedia(
        {
            audio: true,
            video: true
        },
        function (stream) {
            mediaStream = stream;
            mediaStream.stop = function () {
                this.getAudioTracks().forEach(function (track) {
                    track.stop();
                });
                this.getVideoTracks().forEach(function (track) { //in case... :)
                    track.stop();
                });
            };
            /*
             * Rest of your code.....
             * */
        });

    /*
    * somewhere insdie your code you call
    * */
    mediaStream.stop();

Don't use stream.stop(), it's deprecated

MediaStream Deprecations

Use stream.getTracks().forEach(track => track.stop())


Using .stop() on the stream works on chrome when connected via http. It does not work when using ssl (https).


Have a reference of stream form successHandle

var streamRef;

var handleVideo = function (stream) {
    streamRef = stream;
}

//this will stop video and audio both track
streamRef.getTracks().map(function (val) {
    val.stop();
});

The following code worked for me:

public vidOff() {

      let stream = this.video.nativeElement.srcObject;
      let tracks = stream.getTracks();

      tracks.forEach(function (track) {
          track.stop();
      });

      this.video.nativeElement.srcObject = null;
      this.video.nativeElement.stop();
  }

Please check this: https://jsfiddle.net/wazb1jks/3/

_x000D_
_x000D_
navigator.getUserMedia(mediaConstraints, function(stream) {_x000D_
    window.streamReference = stream;_x000D_
}, onMediaError);
_x000D_
_x000D_
_x000D_

Stop Recording

_x000D_
_x000D_
function stopStream() {_x000D_
    if (!window.streamReference) return;_x000D_
_x000D_
    window.streamReference.getAudioTracks().forEach(function(track) {_x000D_
        track.stop();_x000D_
    });_x000D_
_x000D_
    window.streamReference.getVideoTracks().forEach(function(track) {_x000D_
        track.stop();_x000D_
    });_x000D_
_x000D_
    window.streamReference = null;_x000D_
}
_x000D_
_x000D_
_x000D_


Start and Stop Web Camera,(Update 2020 React es6 )

Start Web Camera

stopWebCamera =()=>

       //Start Web Came
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        //use WebCam
        navigator.mediaDevices.getUserMedia({ video: true }).then(stream => {
          this.localStream = stream;
          this.video.srcObject = stream;
          this.video.play();
        });
      }
 }

Stop Web Camera or Video playback in general

stopVideo =()=>
{
        this.video.pause();
        this.video.src = "";
        this.video.srcObject = null;

         // As per new API stop all streams
        if (this.localStream)
          this.localStream.getTracks().forEach(track => track.stop());
}

Stop Web Camera function works even with video streams:

  this.video.src = this.state.videoToTest;
  this.video.play();

Since you need the tracks to close the streaming, and you need the stream boject to get to the tracks, the code I have used with the help of the Muaz Khan's answer above is as follows:

if (navigator.getUserMedia) {
    navigator.getUserMedia(constraints, function (stream) {
        videoEl.src = stream;
        videoEl.play();
        document.getElementById('close').addEventListener('click', function () {
            stopStream(stream);
        });
    }, errBack);

function stopStream(stream) {
console.log('stop called');
stream.getVideoTracks().forEach(function (track) {
    track.stop();
});

Of course this will close all the active video tracks. If you have multiple, you should select accordingly.


You need to stop all tracks (from webcam, microphone):

localStream.getTracks().forEach(track => track.stop());

Suppose we have streaming in video tag and id is video - <video id="video"></video> then we should have following code -

var videoEl = document.getElementById('video');
// now get the steam 
stream = videoEl.srcObject;
// now get all tracks
tracks = stream.getTracks();
// now close each track by having forEach loop
tracks.forEach(function(track) {
   // stopping every track
   track.stop();
});
// assign null to srcObject of video
videoEl.srcObject = null;

You can end the stream directly using the stream object returned in the success handler to getUserMedia. e.g.

localMediaStream.stop()

video.src="" or null would just remove the source from video tag. It wont release the hardware.


Use any of these functions:

// stop both mic and camera
function stopBothVideoAndAudio(stream) {
    stream.getTracks().forEach(function(track) {
        if (track.readyState == 'live') {
            track.stop();
        }
    });
}

// stop only camera
function stopVideoOnly(stream) {
    stream.getTracks().forEach(function(track) {
        if (track.readyState == 'live' && track.kind === 'video') {
            track.stop();
        }
    });
}

// stop only mic
function stopAudioOnly(stream) {
    stream.getTracks().forEach(function(track) {
        if (track.readyState == 'live' && track.kind === 'audio') {
            track.stop();
        }
    });
}

FF, Chrome and Opera has started exposing getUserMedia via navigator.mediaDevices as standard now (Might change :)

online demo

navigator.mediaDevices.getUserMedia({audio:true,video:true})
    .then(stream => {
        window.localStream = stream;
    })
    .catch( (err) =>{
        console.log(err);
    });
// later you can do below
// stop both video and audio
localStream.getTracks().forEach( (track) => {
track.stop();
});
// stop only audio
localStream.getAudioTracks()[0].stop();
// stop only video
localStream.getVideoTracks()[0].stop();

Starting Webcam Video with different browsers

For Opera 12

window.navigator.getUserMedia(param, function(stream) {
                            video.src =window.URL.createObjectURL(stream);
                        }, videoError );

For Firefox Nightly 18.0

window.navigator.mozGetUserMedia(param, function(stream) {
                            video.mozSrcObject = stream;
                        }, videoError );

For Chrome 22

window.navigator.webkitGetUserMedia(param, function(stream) {
                            video.src =window.webkitURL.createObjectURL(stream);
                        },  videoError );

Stopping Webcam Video with different browsers

For Opera 12

video.pause();
video.src=null;

For Firefox Nightly 18.0

video.pause();
video.mozSrcObject=null;

For Chrome 22

video.pause();
video.src="";

With this the Webcam light go down everytime...


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to html5-video

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66? In Chrome 55, prevent showing Download button for HTML 5 video HTML 5 Video "autoplay" not automatically starting in CHROME How to open .mov format video in HTML video Tag? What is a blob URL and why it is used? .mp4 file not playing in chrome HTML5 video won't play in Chrome only use video as background for div HTML5 Video tag not working in Safari , iPhone and iPad Video 100% width and height

Examples related to webrtc

WebRTC vs Websockets: If WebRTC can do Video, Audio, and Data, why do I need Websockets? Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

Examples related to getusermedia

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