Build a WebRTC Video Recorder in React.js Using react-webcam Node Library in Browser Using Javascript Full Project For Beginners

 

 

Welcome folks today in this blog post we will be capturing selfie images and recording video in browser using react.js library called react-webcam. All the full source code of the application is shown below.

 

 

 

Get Started

 

 

 

In order to get started you need to install the below library using the npm command as shown below

 

 

npm i react-webcam

 

 

Demo

 

https://codepen.io/mozmorris/pen/JLZdoP

 

Usage

 

import React from "react";
import Webcam from "react-webcam";
 
const WebcamComponent = () => <Webcam />;

Props

The props here are specific to this component but one can pass any prop to the underlying video tag eg className or style

prop type default notes
audio boolean true enable/disable audio
audioConstraints object MediaStreamConstraint(s) for the audio
forceScreenshotSourceSize boolean false uses size of underlying source video stream (and thus ignores other size related props)
imageSmoothing boolean true pixel smoothing of the screenshot taken
mirrored boolean false show camera preview and get the screenshot mirrored
minScreenshotHeight number min height of screenshot
minScreenshotWidth number min width of screenshot
onUserMedia function noop callback for when component receives a media stream
onUserMediaError function noop callback for when component can’t receive a media stream with MediaStreamError param
screenshotFormat string ‘image/webp’ format of screenshot
screenshotQuality number 0.92 quality of screenshot(0 to 1)
videoConstraints object MediaStreamConstraints(s) for the video
See also  React.js Redux Simple Maths Arithmetic Calculator Using Javascript Full Project For Beginners

 

 

 

Selfie App Example

 

 

const WebcamCapture = () => {
  const webcamRef = React.useRef(null);
  const [imgSrc, setImgSrc] = React.useState(null);

  const capture = React.useCallback(() => {
    const imageSrc = webcamRef.current.getScreenshot();
    setImgSrc(imageSrc);
  }, [webcamRef, setImgSrc]);

  return (
    <>
      <Webcam
        audio={false}
        ref={webcamRef}
        screenshotFormat="image/jpeg"
      />
      <button onClick={capture}>Capture photo</button>
      {imgSrc && (
        <img
          src={imgSrc}
        />
      )}
    </>
  );
};

ReactDOM.render(<WebcamCapture />, document.getElementById("root"));

// https://www.npmjs.com/package/react-webcam

 

 

 

Recording Video Example

 

 

const WebcamStreamCapture = () => {
  const webcamRef = React.useRef(null);
  const mediaRecorderRef = React.useRef(null);
  const [capturing, setCapturing] = React.useState(false);
  const [recordedChunks, setRecordedChunks] = React.useState([]);

  const handleStartCaptureClick = React.useCallback(() => {
    setCapturing(true);
    mediaRecorderRef.current = new MediaRecorder(webcamRef.current.stream, {
      mimeType: "video/webm"
    });
    mediaRecorderRef.current.addEventListener(
      "dataavailable",
      handleDataAvailable
    );
    mediaRecorderRef.current.start();
  }, [webcamRef, setCapturing, mediaRecorderRef]);

  const handleDataAvailable = React.useCallback(
    ({ data }) => {
      if (data.size > 0) {
        setRecordedChunks((prev) => prev.concat(data));
      }
    },
    [setRecordedChunks]
  );

  const handleStopCaptureClick = React.useCallback(() => {
    mediaRecorderRef.current.stop();
    setCapturing(false);
  }, [mediaRecorderRef, webcamRef, setCapturing]);

  const handleDownload = React.useCallback(() => {
    if (recordedChunks.length) {
      const blob = new Blob(recordedChunks, {
        type: "video/webm"
      });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      document.body.appendChild(a);
      a.style = "display: none";
      a.href = url;
      a.download = "react-webcam-stream-capture.webm";
      a.click();
      window.URL.revokeObjectURL(url);
      setRecordedChunks([]);
    }
  }, [recordedChunks]);

  return (
    <>
      <Webcam audio={false} ref={webcamRef} />
      {capturing ? (
        <button onClick={handleStopCaptureClick}>Stop Capture</button>
      ) : (
        <button onClick={handleStartCaptureClick}>Start Capture</button>
      )}
      {recordedChunks.length > 0 && (
        <button onClick={handleDownload}>Download</button>
      )}
    </>
  );
};

ReactDOM.render(<WebcamStreamCapture />, document.getElementById("root"));

// https://www.npmjs.com/package/react-webcam

Leave a Reply