【问题标题】:Closing webcam without reloading关闭网络摄像头而不重新加载
【发布时间】:2018-10-20 11:56:35
【问题描述】:

我是网络开发的初学者,我正在开发一个使用 create-react-app 构建的视频聊天应用程序。我正在使用recordRTC 库从用户的网络摄像头和麦克风进行录制和流式传输。 当我停止录制时,我也想关闭网络摄像头。

import React, { Component } from "react";
import RecordRTC from "recordrtc";

const captureUserMedia = callback => {
  const params = { audio: true, video: true };
  navigator.mediaDevices
    .getUserMedia(params)
    .then(callback)
    .catch((error) => {
      console.error(JSON.stringify(error));
    });
};

export default class Recorder extends Component {
  constructor(props) {
    super(props);
    this.recordVideo = null;
    this.videoRef = React.createRef();
  }

  componentDidMount = () => {
    captureUserMedia(stream => (this.videoRef.current.srcObject = stream));
  };

  startRecord = () => {
    captureUserMedia(stream => {
      this.recordVideo = RecordRTC(stream, { type: "video" });
      this.recordVideo.startRecording();
    });
  };

  stopRecord = () => {
    this.recordVideo.stopRecording();
    this.videoRef.current.srcObject.getTracks().forEach((track) => {
      track.stop();
    });
  };
    render() {
    return (
      <div>
        <video ref={this.videoRef} autoPlay muted />
        <div>
          <button onClick={this.startRecord}>START</button>
          <button onClick={this.stopRecord}>STOP</button>
        </div>
      </div>
    );
  }
}

我在here 找到了一个相关的帖子:

stream.getTracks().forEach((track) => {
    track.stop()
})

这会停止流,但导航器选项卡 (chrome) 上仍然存在红色圆圈,并且网络摄像头的灯仍然是闪电。

如何关闭网络摄像头?

我发现的唯一方法是强制重新加载,但我真的不想这样做......

如果有人有想法,请告诉我。

感谢您的回复:)

【问题讨论】:

  • 请在问题中添加相关代码,而不是链接到它
  • 好的,我做到了...感谢您的回复!

标签: reactjs webcam mediadevices


【解决方案1】:

我发现我做错了!

我调用了两次getUserMedia() 方法而不是一次(使用 captureUserMedia 函数)。

你可以试试下面的代码就OK了!!!

...

  componentDidMount = () => {
    captureUserMedia((stream) => {
      this.videoRef.current.srcObject = stream;
      this.recordVideo = RecordRTC(stream, { type: "video" });
    });
  };

  startRecord = () => {
      this.recordVideo.startRecording();
  };

  stopRecord = () => {
    this.recordVideo.stopRecording();
    this.videoRef.current.srcObject.getTracks().forEach((track) => {
      track.stop();
    });
  };

...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 2022-01-11
    • 1970-01-01
    • 2017-01-29
    • 1970-01-01
    相关资源
    最近更新 更多