简体   繁体   中英

Webcam Light Stays on Even After I run MediaStreamTrack.stop()

I am building a react app and need to access the webcam which get with the following code:

navigator.mediaDevices.getUserMedia({ video: true, audio: false })
  .then(function(stream) {
      video.srcObject = stream;
      window.localstream = stream;
      video.play();
  })

However, when I unmount the current component, my webcam stays on. In my componentWillUnmount block, I have tried the following code.

video.pause();
video.srcObject=null;
window.localstream.getTracks()[0].stop();
window.localstream.getVideoTracks()[0].stop();

My webcam light still stays on however. When I console.log the mediaStreamTrack afterwards, I get:

在此处输入图片说明

How do I stop my webcam?

  1. If you are using multiple cameras, then you need to make sure that your code is trying to "stop" the same camera as you turn on before.

  2. You need to make sure your code only call getUserMedia once, then getVideoTracks()[0].stop() should work fine.

This post looks old, for those who have the same problem, try this approach

 let tracks = window.localstream.getTracks();
 let video = document.querySelector('#your-video-tag-id');
 tracks.forEach(function(track) {
     if (track.kind === 'video') {
         if (track.enabled) {
             track.stop();
             track.enabled = false; 
         }
     }
 });
 video.srcObject = null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM