在ComponentWillUnmount中的React Component中停止网络摄像头

时间:2019-06-13 01:53:39

标签: reactjs

我有一个react组件,当安装VideoPage组件时,它会启动网络摄像头

但是,当我转到另一个页面时,摄像头仍在后台运行,这是因为笔记本电脑的摄像头灯仍然亮起

我认为退出组件时,需要在React生命周期方法ComponentWillUnmount中“杀死”网络摄像头。我该怎么做?

下面是我的代码...请多指教。谢谢

从“反应”导入React;

export default class VideoPage extends React.Component {
  constructor(props) {
    super(props);

    this.videoTag = React.createRef();

    this.state = {
      loading: false
    };
  }

  componentDidMount() {
    navigator.mediaDevices
      .getUserMedia({ video: true })
      .then(this.handleStream)
      .catch(err => console.log(err));
  }

  handleStream = async stream => {
    // start receiving stream from webcam
    this.videoTag.current.srcObject = stream;

    console.log("The video is ready");
  };

  render() {
    return (
      <div>
        <div style={{ paddingTop: 20 }}>
          <video
            id="myvideo"
            ref={this.videoTag}
            width={426}
            height={240}
            autoPlay
            title="video"
          />
        </div>
      </div>
    );
  }
}

2 个答案:

答案 0 :(得分:1)

要停止getUserMedia请求,您需要调用生成的stop()MediaStreamTracks方法。
要访问这些MediaStreamTrack,您需要调用在stream方法中收到的handleStream MediaStream的getTracks()方法。

因此,最好将流保存在实例中的某个位置,例如保存为this.stream
然后在您的componentWillUnmount中,您将致电

this.stream.getTracks()
  .forEach((track) => track.stop());

答案 1 :(得分:0)

感谢@Kalido的回答,我的最终工作代码如下...

完整的代码可以在这里找到... Github Repo

  constructor(props) {
    // set up constructor
    super(props);

    // create video ref
    this.videoTag = React.createRef();
    this.myStream = null;

    // set up initial state
    this.state = {
      guess: "",
      probability: null,
      loading: false,
      scale: defaultValue
    };
  }

  componentDidMount() {
    // set up webcam when component mounting
    navigator.mediaDevices
      .getUserMedia({ video: true })
      .then(this.handleStream)
      .catch(err => console.log(err));
  }

  componentWillUnmount() {
    this.myStream.getTracks().forEach(track => track.stop());
  }

  handleStream = async stream => {
    this.myStream = stream;

    // start receiving stream from webcam
    this.videoTag.current.srcObject = stream;

    // prepare classifier and assign myClassifier in global scope
    myClassifier = await this.prepareClassifier(this.videoTag.current);
    console.log(myClassifier);
    console.log("The video is ready");
  };