8

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:

enter image description here

How do I stop my webcam?

pengcheng95
  • 292
  • 4
  • 13

2 Answers2

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

Wei Ni
  • 71
  • 1
  • 3
1

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

import * as React from "react";

// in your component

const video = React.useRef();
const tracks = window.localstream.getTracks();

tracks.forEach((track) => {
  if (track.kind === "video") {
    if (track.enabled) {
      track.stop();
      track.enabled = false;
    }
  }
});

video.current.srcObject = null;
zero_cool
  • 3,960
  • 5
  • 39
  • 54
  • It is not a good idea to use `document.querySelector` in react. You can instead use `useRef` for that purpose. [more info](https://bobbyhadz.com/blog/react-document-queryselector) – Hamed Siaban Nov 09 '22 at 08:36
  • You're right, I hadn't noticed that he was referring to a react application. – Muller Roufaou Dec 25 '22 at 19:32