1.1.5 • Published 1 month ago

react-record-webcam v1.1.5

Weekly downloads
149
License
MIT
Repository
github
Last release
1 month ago

TypeScript Tests npm version

React Record Webcam is a promise-based, zero-dependency webcam library for React, enabling the selection of video and audio inputs for single or multiple concurrent recordings with any mix of video and audio sources.

Demo

Try the example on StackBlitz

Add package

npm i react-record-webcam

Quick Start

To start recording, create a recording instance using createRecording and manage the recording process with the hook's methods:

import { useRecordWebcam } from 'react-record-webcam'

const App = () => {
  const { createRecording, openCamera, startRecording, stopRecording, downloadRecording } = useRecordWebcam()

  const recordVideo = async () => {
    const recording = await createRecording();
    await openCamera(recording.id);
    await startRecording(recording.id);
    await new Promise(resolve => setTimeout(resolve, 3000)); // Record for 3 seconds
    await stopRecording(recording.id);
    await downloadRecording(recording.id); // Download the recording
  };

  return <button onClick={recordVideo}>Record Video</button>;
};

Usage and Examples

Each method in the hook always returns an updated instance of a recording. Pass the id of the recording instance to any of the methods from the hook to open camera, start, pause or stop a recording:

Heres an example of uploading the recorded blob to a back-end service:

const { createRecording, openCamera, startRecording, stopRecording } = useRecordWebcam()


async function record() {
    const recording = await createRecording();

    await openCamera(recording.id);
    await startRecording(recording.id);
    await new Promise((resolve) => setTimeout(resolve, 3000)); // Record for 3 seconds
    const recorded = await stopRecording(recording.id);

    // Upload the blob to a back-end
    const formData = new FormData();
    formData.append('file', recorded.blob, 'recorded.webm');

    const response = await fetch('https://your-backend-url.com/upload', {
        method: 'POST',
        body: formData,
    });
};

All recording instances are available in activeRecordings. You can for example access refs for webcam feed and recording preview in your component:

const { activeRecordings } = useRecordWebcam()

...

  {activeRecordings.map(recording => (
    <div key={recording.id}>
      <video ref={recording.webcamRef} autoPlay />
      <video ref={recording.previewRef} autoPlay loop />
    </div>
  ))}

Recording instance

PropertyTypeDescription
idstringThe ID of the recording.
audioIdstringThe ID of the audio device.
audioLabelstringThe label of the audio device.
blobBlobThe blob of the recording.
blobChunksBlob[]Single blob or chunks per timeslice of the recording.
fileNamestringThe name of the file.
fileTypestringThe type of the file.
isMutedbooleanWhether the recording is muted.
mimeTypestringThe MIME type of the recording.
objectURLstring | nullThe object URL of the recording.
previewRefReact.RefObject<HTMLVideoElement>React Ref for the preview element.
recorderMediaRecorderThe MediaRecorder instance of the recording.
status'INITIAL' | 'CLOSED' | 'OPEN' | 'RECORDING' | 'STOPPED' | 'ERROR' | 'PAUSED'The status of the recording.
videoIdstringThe ID of the video device.
videoLabelstringThe label of the video device.
webcamRefReact.RefObject<HTMLVideoElement>React Ref for the webcam element.

Configuring options

Pass options either when initializing the hook or at any point in your application logic using applyOptions.

// At initialization
const { applyOptions, applyConstraints } = useRecordWebcam({
  options: { fileName: 'custom-name', fileType: 'webm', timeSlice: 1000 },
  mediaRecorderOptions: { mimeType: 'video/webm; codecs=vp8' },
  mediaTrackConstraints: { video: true, audio: true }
});

// Dynamically applying options
applyOptions(recording.id, { fileName: 'updated-name' }); // Update file name
applyConstraints(recording.id, { aspectRatio: 0.56 }) // Change aspect ratio to portrait

List of options

Optionpropertydefault value
fileNameFile nameDate.now()
fileTypeFile type for download (will override inferred type from mimeType)'webm'
timeSliceRecording intervalundefined

Both mediaRecorderOptions and mediatrackConstraints mirror the official API. Please see on MDN for available options:

MDN: mediaRecorderOptions

MDN: mediatrackConstraints

Codec Support

A codec supported by the current browser will be detected and used for recordings.

To see all video and audio codecs supported by the browser:

const { supportedAudioCodecs, supportedVideoCodecs } = useRecordWebcam();

console.log({ supportedAudioCodecs, supportedVideoCodecs })

To check the support of a specific codec:

const { checkCodecRecordingSupport, checkVideoCodecPlaybackSupport } = useRecordWebcam()

const codec = 'video/x-matroska;codecs=avc1'
const isRecordingSupported = checkCodecRecordingSupport(codec)
const isPlayBackSupported = checkVideoCodecPlaybackSupport(codec)

To use a specific codec, pass this in the mediaRecorderOptions. Note that MediaRecorder uses a mimeType format for the codec: <container>;codec=<videoCodec>,<audioCodec>

const codec = 'video/webm;codecs=h264'
const mediaRecorderOptions = { mimetype: codec }
const recordWebcam = useRecordWebcam({ mediaRecorderOptions })

For more info see the codec guide on MDN.

Error handling

Error messages are available in the hook. You can import the constant of all messages for error handling from the package.

import { useRecordWebcam, ERROR_MESSAGES } from 'react-record-webcam';

const { errorMessage } = useRecordWebcam();

if (errorMessage === ERROR_MESSAGES.NO_USER_PERMISSION) {
  // Handle specific error scenario
}

API Reference

Method/PropertyArgumentsReturnsDescription
activeRecordingsRecording[]Array of active recordings.
applyConstraintsrecordingId: string, constraints: MediaTrackConstraintsPromise<Recording \| void>Applies given constraints to the camera for a specific recording.
applyRecordingOptionsrecordingId: stringPromise<Recording \| void>Applies recording options to a specific recording.
cancelRecordingrecordingId: stringPromise<void>Cancels the current recording session.
clearAllRecordingsPromise<void>Clears all active recordings.
clearErrorvoidFunction to clear the current error message.
clearPreviewrecordingId: stringPromise<Recording \| void>Clears the preview of a specific recording.
closeCamerarecordingId: stringPromise<Recording \| void>Closes the camera for a specific recording.
createRecordingvideoId?: string, audioId?: stringPromise<Recording \| void>Creates a new recording session with specified video and audio sources.
devicesByIdByIdObject containing devices by their ID, where ById is a record of string to { label: string; type: 'videoinput' \| 'audioinput'; }.
devicesByTypeByTypeObject categorizing devices by their type, where ByType has video and audio arrays of { label: string; deviceId: string; }.
downloadrecordingId: stringPromise<void>Downloads a specific recording.
errorMessagestring \| nullThe current error message, if any, related to recording.
muteRecordingrecordingId: stringPromise<Recording \| void>Mutes or unmutes the recording audio.
openCamerarecordingId: stringPromise<Recording \| void>Opens the camera for a specific recording with optional constraints.
pauseRecordingrecordingId: stringPromise<Recording \| void>Pauses the current recording.
resumeRecordingrecordingId: stringPromise<Recording \| void>Resumes a paused recording.
startRecordingrecordingId: stringPromise<Recording \| void>Starts a new recording session.
stopRecordingrecordingId: stringPromise<Recording \| void>Stops the current recording session.

|

License

MIT

Credits

webcam by iconfield from Noun Project (CC BY 3.0)

1.1.5

1 month ago

1.1.4

1 month ago

1.1.3

1 month ago

1.1.2

2 months ago

1.1.1

2 months ago

1.1.0

2 months ago

1.0.0-rc.0

2 months ago

1.1.0-rc.1

2 months ago

1.0.1

3 months ago

1.0.0

7 months ago

1.0.0-rc.3

7 months ago

1.0.0-rc.1

7 months ago

1.0.0-rc.2

7 months ago

0.0.15

2 years ago

0.0.16

2 years ago

0.0.17

2 years ago

0.0.18

2 years ago

0.0.12

3 years ago

0.0.13

3 years ago

0.0.14

3 years ago

0.0.11

3 years ago

0.0.10

3 years ago

0.0.9

3 years ago

0.0.8

3 years ago

0.0.7

3 years ago

0.0.6

3 years ago

0.0.5

4 years ago

0.0.4

4 years ago

0.0.3

4 years ago

0.0.2

4 years ago

0.0.1

4 years ago