### Install react-media-recorder with npm
Source: https://github.com/deltacircuit/react-media-recorder/blob/master/README.md
Use npm to install the react-media-recorder package.
```bash
npm i react-media-recorder
```
--------------------------------
### Install react-media-recorder with yarn
Source: https://github.com/deltacircuit/react-media-recorder/blob/master/README.md
Use yarn to install the react-media-recorder package.
```bash
yarn add react-media-recorder
```
--------------------------------
### Screen Recording with Audio and Custom Video Constraints
Source: https://context7.com/deltacircuit/react-media-recorder/llms.txt
Enables screen recording, optionally including microphone audio. This example configures specific video constraints like resolution and frame rate, sets the MIME type for the recording, and uses `stopStreamsOnStop` to ensure streams are properly terminated. It also demonstrates how to exclude the current tab from screen sharing options using `selfBrowserSurface`.
```typescript
import { useReactMediaRecorder } from "react-media-recorder";
const ScreenRecorder = () => {
const {
status,
startRecording,
stopRecording,
mediaBlobUrl,
error,
} = useReactMediaRecorder({
screen: true,
audio: true, // Include microphone audio
video: {
width: 1920,
height: 1080,
frameRate: 30,
},
selfBrowserSurface: "exclude", // Exclude current tab from options
preferCurrentTab: false,
mediaRecorderOptions: {
mimeType: "video/webm;codecs=vp9",
videoBitsPerSecond: 2500000,
},
stopStreamsOnStop: true,
});
return (
Status: {status}
{error &&
Error: {error}
}
{mediaBlobUrl && (
)}
);
};
```
--------------------------------
### Basic Video Recording with useReactMediaRecorder Hook
Source: https://context7.com/deltacircuit/react-media-recorder/llms.txt
Demonstrates basic video recording using the `useReactMediaRecorder` hook. It includes controls for starting, stopping, pausing, resuming, and clearing recordings, along with displaying the recording status and any errors. A live preview of the recorded video is shown.
```typescript
import { useReactMediaRecorder } from "react-media-recorder";
// Basic video recording
const VideoRecorder = () => {
const {
status,
startRecording,
stopRecording,
pauseRecording,
resumeRecording,
mediaBlobUrl,
error,
clearBlobUrl,
} = useReactMediaRecorder({ video: true });
return (
Status: {status}
{error &&
Error: {error}
}
{mediaBlobUrl && }
);
};
```
--------------------------------
### Handle Recording Errors with Custom Messages
Source: https://context7.com/deltacircuit/react-media-recorder/llms.txt
Implement robust error handling for media recording. This snippet maps specific error codes to user-friendly messages, guiding users on how to resolve issues like permission denial or device conflicts.
```typescript
import { useReactMediaRecorder, RecorderErrors } from "react-media-recorder";
const RobustRecorder = () => {
const { status, startRecording, stopRecording, mediaBlobUrl, error } =
useReactMediaRecorder({
video: true,
audio: true,
askPermissionOnMount: true,
});
const getErrorMessage = (errorCode: string): string => {
const errorMessages: Record = {
media_aborted: "Recording was aborted by the system.",
permission_denied: "Camera/microphone permission was denied. Please allow access in browser settings.",
no_specified_media_found: "No camera or microphone found on this device.",
media_in_use: "Camera or microphone is being used by another application.",
invalid_media_constraints: "The specified media constraints are not supported.",
no_constraints: "No audio or video constraints were specified.",
recorder_error: "An error occurred with the media recorder.",
};
return errorMessages[errorCode] || "An unknown error occurred.";
};
return (
Status: {status}
{error && (
Error: {getErrorMessage(error)}
)}
{mediaBlobUrl && }
);
};
```
--------------------------------
### Video Preview with React Media Recorder
Source: https://github.com/deltacircuit/react-media-recorder/blob/master/README.md
Demonstrates how to use the `previewStream` prop to display a live video preview to the user. The stream is muted by default to prevent audio feedback.
```tsx
const VideoPreview = ({ stream }: { stream: MediaStream | null }) => {
const videoRef = useRef(null);
useEffect(() => {
if (videoRef.current && stream) {
videoRef.current.srcObject = stream;
}
}, [stream]);
if (!stream) {
return null;
}
return ;
};
const App = () => (
{
return ;
}}
/>
);
```
--------------------------------
### Live Video Preview with useReactMediaRecorder
Source: https://context7.com/deltacircuit/react-media-recorder/llms.txt
Displays a live preview of the camera feed during recording. Requires the 'previewStream' from the hook. Ensure 'video: true' is set in the hook options.
```typescript
import {
useReactMediaRecorder
} from "react-media-recorder";
import {
useEffect,
useRef
} from "react";
const VideoPreview = ({ stream }: { stream: MediaStream | null }) => {
const videoRef = useRef(null);
useEffect(() => {
if (videoRef.current && stream) {
videoRef.current.srcObject = stream;
}
}, [stream]);
if (!stream) return null;
return ;
};
const LivePreviewRecorder = () => {
const {
status,
startRecording,
stopRecording,
mediaBlobUrl,
previewStream,
} = useReactMediaRecorder({
video: true,
audio: true,
askPermissionOnMount: true, // Request permissions immediately
});
return (
);
};
```
--------------------------------
### Usage with React Hooks
Source: https://github.com/deltacircuit/react-media-recorder/blob/master/README.md
Shows how to integrate react-media-recorder using the useReactMediaRecorder hook for managing recording state and controls within a functional component.
```javascript
import { useReactMediaRecorder } from "react-media-recorder";
const RecordView = () => {
const { status, startRecording, stopRecording, mediaBlobUrl } =
useReactMediaRecorder({ video: true });
return (
{status}
);
};
```
--------------------------------
### Usage with React Component (Render Prop)
Source: https://github.com/deltacircuit/react-media-recorder/blob/master/README.md
Demonstrates how to use the ReactMediaRecorder component with a render prop to manage recording status, start/stop functions, and display the recorded media.
```javascript
import { ReactMediaRecorder } from "react-media-recorder";
const RecordView = () => (
(
{status}
)}
/>
);
```
--------------------------------
### Default Media Recorder Options
Source: https://github.com/deltacircuit/react-media-recorder/blob/master/README.md
An empty object is the default for mediaRecorderOptions, which are passed directly to the MediaRecorder constructor.
```javascript
{}
```
--------------------------------
### Real-time Audio Visualization with Canvas
Source: https://context7.com/deltacircuit/react-media-recorder/llms.txt
Visualize audio input in real-time using the HTML Canvas element. This component processes the audio stream to draw frequency-based bars, providing visual feedback during recording.
```typescript
import { useReactMediaRecorder } from "react-media-recorder";
import { useEffect, useRef } from "react";
const AudioVisualizer = ({ stream }: { stream: MediaStream | null }) => {
const canvasRef = useRef(null);
const animationRef = useRef();
useEffect(() => {
if (!stream || !canvasRef.current) return;
const audioContext = new AudioContext();
const analyser = audioContext.createAnalyser();
const source = audioContext.createMediaStreamSource(stream);
source.connect(analyser);
analyser.fftSize = 256;
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
const canvas = canvasRef.current;
const ctx = canvas.getContext("2d")!;
const draw = () => {
analyser.getByteFrequencyData(dataArray);
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
const barWidth = (canvas.width / bufferLength) * 2.5;
let x = 0;
for (let i = 0; i < bufferLength; i++) {
const barHeight = dataArray[i] / 2;
ctx.fillStyle = `rgb(${barHeight + 100}, 50, 50)`;
ctx.fillRect(x, canvas.height - barHeight, barWidth, barHeight);
x += barWidth + 1;
}
animationRef.current = requestAnimationFrame(draw);
};
draw();
return () => {
if (animationRef.current) cancelAnimationFrame(animationRef.current);
audioContext.close();
};
}, [stream]);
return ;
};
const RecorderWithVisualizer = () => {
const { status, startRecording, stopRecording, mediaBlobUrl, previewAudioStream } =
useReactMediaRecorder({ audio: true, video: false, askPermissionOnMount: true });
return (
Status: {status}
{mediaBlobUrl && }
);
};
```
--------------------------------
### Custom MediaStream Recording with useReactMediaRecorder
Source: https://context7.com/deltacircuit/react-media-recorder/llms.txt
Records using a custom MediaStream, ideal for canvas-based content or stream combinations. Set 'customMediaStream' in hook options and 'stopStreamsOnStop: false' to keep the custom stream active.
```typescript
import {
useReactMediaRecorder
} from "react-media-recorder";
import {
useEffect,
useRef,
useState
} from "react";
const CanvasRecorder = () => {
const canvasRef = useRef(null);
const [customStream, setCustomStream] = useState(null);
useEffect(() => {
if (canvasRef.current) {
// Create a stream from the canvas at 30fps
const stream = canvasRef.current.captureStream(30);
setCustomStream(stream);
// Example: animate something on the canvas
const ctx = canvasRef.current.getContext("2d");
let frame = 0;
const animate = () => {
if (ctx) {
ctx.fillStyle = `hsl(${frame % 360}, 70%, 50%)`;
ctx.fillRect(0, 0, 640, 480);
ctx.fillStyle = "white";
ctx.font = "48px Arial";
ctx.fillText(`Frame: ${frame}`, 200, 250);
}
frame++;
requestAnimationFrame(animate);
};
animate();
}
}, []);
const {
status,
startRecording,
stopRecording,
mediaBlobUrl,
} = useReactMediaRecorder({
customMediaStream: customStream,
video: true,
stopStreamsOnStop: false, // Keep canvas stream alive
});
return (
Status: {status}
{mediaBlobUrl && }
);
};
```
--------------------------------
### ReactMediaRecorder Render-Prop Component
Source: https://context7.com/deltacircuit/react-media-recorder/llms.txt
Provides a render-prop API for the media recorder, suitable for class components or declarative patterns. Handles recording controls and playback. The 'render' prop receives all recorder states and methods.
```typescript
import {
ReactMediaRecorder
} from "react-media-recorder";
const RecordingComponent = () => (
{
console.log("Recorded blob:", blob);
}}
render={({
status,
startRecording,
stopRecording,
pauseRecording,
resumeRecording,
mediaBlobUrl,
error,
previewStream,
isAudioMuted,
muteAudio,
unMuteAudio,
clearBlobUrl,
}) => (
Recording Status: {status}
{error &&
Error: {error}
}
{mediaBlobUrl && (
)}
)}
/>
);
```
--------------------------------
### ReactMediaRecorder Props
Source: https://github.com/deltacircuit/react-media-recorder/blob/master/README.md
This section details the props available for the ReactMediaRecorder component, which are accessible within the `render` function's callback.
```APIDOC
## ReactMediaRecorder Props
### error
A string enum representing the error that occurred during media recording. Possible values include:
- `media_aborted`
- `permission_denied`
- `no_specified_media_found`
- `media_in_use`
- `invalid_media_constraints`
- `no_constraints`
- `recorder_error`
### status
A string enum indicating the current status of the media recorder. Possible values include:
- `idle`
- `acquiring_media`
- `recording`
- `stopping`
- `stopped`
- `media_aborted`
- `permission_denied`
- `no_specified_media_found`
- `media_in_use`
- `invalid_media_constraints`
- `no_constraints`
- `recorder_error`
### startRecording
A function that initiates the media recording process when called.
### pauseRecording
A function that temporarily halts the ongoing media recording when called.
### resumeRecording
A function that resumes a paused media recording when called.
### stopRecording
A function that terminates the media recording process when called.
### muteAudio
A function that mutes the audio tracks of the media stream.
### unmuteAudio
A function that unmutes the audio tracks of the media stream.
### mediaBlobUrl
A Blob URL that can be used to reference the recorded media. This URL can be assigned to the `src` attribute of `