Skip to content

useMediaRecorder

Generate a recorded (video/audio) from a media stream object using the media recorder with its state and controller methods.

Options

WARNING

You should always set the type options to a supported Mediarecorder MIME type to get the best results, for example:

tsx
const recorder = useMediaRecorder({ mimeType: 'video/webm;codecs=vp9,opus' });
const recorder = useMediaRecorder({ mimeType: 'video/webm;codecs=vp9,opus' });

Return Values

NameTypeDescription
isActiveBooleanindicates if the recorder is active (paused or recording) or not.
isRecordingBooleanindicates if the recorder is recording or not.
isPausedBooleanindicates if the recorder is paused or not.
errorUnknowncached error if it exists.
startFunctionthe start recording function, and it takes the MediaStream object, and an optional timeslice value.
stopFunctionthe stop function that takes the type of the recorded (video/audio) (default is video/mp4) as an option, and return a recorded Blob object in a Primise.
pauseFunctionpause the recording.
resumeFunctionresume the recording.
togglePlayStateFunctiontoggle between pause and resume, and it can take a boolean to force it.

Example Usage

tsx
import { useMediaDevices, useMediaRecorder } from 'react-pre-hooks';

export default function VideoRecorder() {
  const media = useMediaDevices({ startOnMount: false });
  const recorder = useMediaRecorder({ mimeType: 'video/webm;codecs=vp8' });

  const handleClick = async () => {
    if (recorder.isRecording) {
      const blob = await recorder.stop({ type: 'video/mp4' });
      download(URL.createObjectURL(blob));

      media.stop();
    } else {
      await media.start({ video: true, audio: true });

      recorder.start(media.stream.current);
    }
  };

  return (
    <main>
      <video ref={media.ref} />
      <button onClick={handleClick}>
        {recorder.isRecording ? 'stop' : 'start'} Recording
      </button>
    </main>
  );
}
import { useMediaDevices, useMediaRecorder } from 'react-pre-hooks';

export default function VideoRecorder() {
  const media = useMediaDevices({ startOnMount: false });
  const recorder = useMediaRecorder({ mimeType: 'video/webm;codecs=vp8' });

  const handleClick = async () => {
    if (recorder.isRecording) {
      const blob = await recorder.stop({ type: 'video/mp4' });
      download(URL.createObjectURL(blob));

      media.stop();
    } else {
      await media.start({ video: true, audio: true });

      recorder.start(media.stream.current);
    }
  };

  return (
    <main>
      <video ref={media.ref} />
      <button onClick={handleClick}>
        {recorder.isRecording ? 'stop' : 'start'} Recording
      </button>
    </main>
  );
}

Released under the MIT License.