admin管理员组

文章数量:1127937

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?

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?

Share Improve this question edited Nov 7, 2022 at 0:59 Dharman 33.2k27 gold badges101 silver badges146 bronze badges asked Jul 25, 2012 at 4:51 Shih-En ChouShih-En Chou 4,1656 gold badges21 silver badges27 bronze badges 0
Add a comment  | 

17 Answers 17

Reset to default 356

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)

Use any of these functions:

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

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

// stop only mic
function stopAudioOnly(stream) {
    stream.getTracks().forEach((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())

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

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;

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

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

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.

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.

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

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

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

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

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

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

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

Stop Recording

function stopStream() {
    if (!window.streamReference) return;

    window.streamReference.getAudioTracks().forEach(function(track) {
        track.stop();
    });

    window.streamReference.getVideoTracks().forEach(function(track) {
        track.stop();
    });

    window.streamReference = null;
}

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

I tried everything, but it worked only intermittently. It was not until I close the component in React that the camera light disappears. I would suggest create your component where you hide/show the component, in order to remove the camera completely.


    const stream = document.querySelector("video").srcObject;
    console.log("videoElement", stream, stream.active);

    stream?.getVideoTracks()?.forEach((track) => {
      console.log("track 1", track);
      track.stop();
      stream?.removeTrack(track);
      track = null;
      console.log("track 2", track);
    });
    stream?.getTracks()?.forEach((track) => {
      console.log("track 3", track);
      track.stop();
      stream?.removeTrack(track);
      track = null;
      console.log("track 4", track);
    });
    stream?.getAudioTracks()?.forEach((track) => {
      console.log("track 5", track);
      track.stop();
      stream?.removeTrack(track);
      track = null;
      console.log("track 6", track);
    });
    console.log("videoElement 2", stream, stream.active);
    stream = null;

    const videoElem = document.querySelector("video");
    if (videoElem) {
      console.log("element exists", videoElem);
      videoElem.pause();
      videoElem.removeAttribute("src");
      videoElem.src = "";
      videoElem.remove();
      console.log("element exists 2", videoElem);
    }

Because the above didn't close the camera completely, I would suggest you would have your component

const [isCameraOn, setCameraOn] = useState(false)

set your video component like this

{isCameraOn && (<YourVideoComponent/>)}

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

本文标签: javascriptStopClose webcam stream which is opened by navigatormediaDevicesgetUserMediaStack Overflow