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

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();
        }
    });
}

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

MediaStream Deprecations

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


EDIT

Since this answer has been originally posted the browser API has changed. .stop() is no longer available on the stream that gets passed to the callback. The developer will have to access the tracks that make up the stream (audio or video) and stop each of them individually.

More info here: https://developers.google.com/web/updates/2015/07/mediastream-deprecations?hl=en#stop-ended-and-active

Example (from the link above):

stream.getTracks().forEach(function(track) {
  track.stop();
});

Browser support may differ.

Original answer

navigator.getUserMedia provides you with a stream in the success callback, you can call .stop() on that stream to stop the recording (at least in Chrome, seems FF doesn't like it)


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();