简体   繁体   English

ReactJS-来自网络摄像头的视频流不起作用

[英]ReactJS - video stream from webcam not working

I'm not sure why this isn't working. 我不确定为什么这行不通。 I'm getting the camera stream and it's working because I'm getting the light on my camera. 我正在获取摄像头流,并且可以正常工作,因为我正在摄像头上取光。

The stream just doesn't seem to be attaching. 流似乎没有附着。



class VideoOutput extends React.Component {
    constructor(props) {
        super(props);
        this.videoRef = React.createRef();
    }

    componentDidMount() {
        const videoObj = this.videoRef.current;
        videoObj.srcObject = this.props.video;
        console.log(videoObj);
    }

    render() {
        return <video ref={this.videoRef}></video>;
    }
}


class Application extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      video: null
    };

    this.handleVideoClick = this.handleVideoClick.bind(this);
  }


  async getVideo() {
    const video = await navigator.mediaDevices.getUserMedia({
      audio: false,
      video: true
    });
    this.setState({ video });
  }

  stopVideo() {
    this.state.video.getTracks().forEach(track => track.stop());
    this.setState({ video: null });
  }


  handleVideoClick() {
    if (this.state.video) {
      this.stopVideo();
    } else {
      this.getVideo();
    } 
  }

  render(){
    return(
      <div>
          <button onClick={this.handleVideoClick}>
            {this.state.video ? 'Vid On' : 'Vid Off'}
          </button>
      <div>
      {this.state.video ? <VideoOutput video={this.state.video} /> : ''}
       </div>
       </div>
    );
  }


}

ReactDOM.render(<Application />, document.getElementById('root'));

Non-functioning example here: https://codepen.io/Chenzo/pen/QXXVvr 此处无法正常运行的示例: https//codepen.io/Chenzo/pen/QXXVvr

This seems like it should work to me... but I suspect I'm missing something simple. 这似乎应该对我有用...但是我怀疑我缺少一些简单的东西。

I suspect the problem is that you're not playing the video. 我怀疑问题是您没有在播放视频。 Try adding this after you set the srcObject : 设置srcObject后,尝试添加以下srcObject

videoObj.play();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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