Search code examples
javascripthtmlhtml5-videowebrtcgetusermedia

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?


Solution

  • 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.

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