useMediaRecorder
Generate a recorded (video/audio) from a media stream object using the media recorder with its state and controller methods.
Options
- It takes the MediaRecorder 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
Name | Type | Description |
---|---|---|
isActive | Boolean | indicates if the recorder is active (paused or recording) or not. |
isRecording | Boolean | indicates if the recorder is recording or not. |
isPaused | Boolean | indicates if the recorder is paused or not. |
error | Unknown | cached error if it exists. |
start | Function | the start recording function, and it takes the MediaStream object, and an optional timeslice value. |
stop | Function | the 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. |
pause | Function | pause the recording. |
resume | Function | resume the recording. |
togglePlayState | Function | toggle 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>
);
}