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

Shih-En Chou picture Shih-En Chou · Jul 25, 2012 · Viewed 134.9k times · Source

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.

Answer

andrei picture andrei · Sep 15, 2012

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)