mozmorris/react-webcam

[Question] How to start react-webcam after it is stopped?

briliantnugraha opened this issue · 0 comments

Hi @mozmorris, thanks for this awesome package that I could use webcam across different devices easily.

I am a beginner on React, I have a question, how to start the webcam again after it has been stopped?
My flow is as follows:

  • [working] npm start -> allow webcam -> click stop button -> webcam vanishes.
  • [not working] click start button -> webcam reappear.

If we want to add a start on the react-webcam, what variable/how do we do it? Is there a basic tutorial on it?
FYI, I have seen this post on a round about way to do it, but it seems that what it did was hiding the div, whereas the video is in fact still on.

Following the tutorial from here, my webcam component looks like this:

  • useRef (it works for stopping, but the value afterward will be null).
  • stop func (following from the link above).
  • start func (not working due to null value from this.webcam after it has been stopped).
import Webcam from "react-webcam";
import React, { Component } from 'react';

class WebcamINT extends Component {
  setRef = (webcam) => {
    this.webcam = webcam;
  }

  stop = () => {
    const mytrack = this.webcam.video.srcObject.getTracks();
    
    mytrack.forEach(track => track.stop());
    //this.webcam.video.srcObject = null;
    console.log("stop is triggered");
  };

  start = () => {
    const mytrack = this.webcam.video.srcObject.getTracks();
    
    mytrack.forEach(track => track.start());
    console.log("start is triggered");
  }

  render() {
    return (
      <div>
        <Webcam
          audio={false}
          ref={this.setRef}
        />
        <br />
        <button onClick={this.start}>Start</button>
        <button onClick={this.stop}>Stop</button>
      </div>
    );
  }
}

export default WebcamINT;

[UPDATE] I've solved the issue when the source Object is null by commenting the line of code on stop function. But when I click the start button, the webcam is still not reappearing.