Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This seems like it should work to me... but I suspect I'm missing something simple.

like image 281
Chenzo Avatar asked Jul 15 '19 22:07

Chenzo


1 Answers

I suspect the problem is that you're not playing the video. Try adding this after you set the srcObject:

videoObj.play();
like image 137
Brad Avatar answered Sep 25 '22 04:09

Brad