Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-record-webcam

Package Overview
Dependencies
Maintainers
1
Versions
31
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-record-webcam

Webcam recording tool for React

  • 1.1.0
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source
React Record Webcam Logo

TypeScript Tests npm version

Promise based zero dependency webcam library for React. Select video and audio input for one or multiple concurrent recordings using any mix of video and audio source.

DEMO

Note version 1.0 is a complete rewrite so you will need to make some changes if updating.


Add package

npm i react-record-webcam

Usage

// record a 3s. video

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

...

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

  const example = async () => {
    try {
      const recording = await createRecording();
      if (!recording) return;
      await openCamera(recording.id);
      await startRecording(recording.id);
      await new Promise((resolve) => setTimeout(resolve, 3000));
      await stopRecording(recording.id);
    } catch (error) {
      console.error({ error });
    }
  };

  return (
    <div>
      <button onClick={example}>Start</button>
      {activeRecordings.map(recording => (
        <div key={recording.id}>
          <video ref={recording.webcamRef} autoPlay muted />
          <video ref={recording.previewRef} autoPlay muted loop />
        </div>
      ))}
    </div>
  )

...

Check the CodeSandbox links for above demo and one with more features.


Passing options

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

const options = { ... }
const mediaRecorderOptions = { ... }
const mediaTrackConstraints =  { ... }

const { ... } = useRecordWebcam({ 
  options, 
  mediaRecorderOptions, 
  mediaTrackConstraints
})

// or

const { applyOptions } = useRecordWebcam() // use utility
applyOptions(recording.id: string, options: Options) // add to your application logic


Optionpropertydefault value
fileNameDate.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

The default codec is set to video/webm;codecs=vp9. If you prefer to use another one, you can check the compatibility for playback and recording with the following utilities:

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:

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

Current error message is passed from the hook, along with a object of error states which you can use for checks.

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

const { errorMessage } = useRecordWebcam()

...
const isUserPermissionDenied = errorMessage === ERROR_MESSAGES.NO_USER_PERMISSION;
...

Full API

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)

Keywords

FAQs

Package last updated on 01 Mar 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc