Skip to content

πŸŽ₯ Make videos programmatically with React

refinement

Jonny Burger92794baf72ae
diff --git a/packages/skills/skills/remotion/rules/calculate-metadata.md b/packages/skills/skills/remotion/rules/calculate-metadata.md
index 06098cad42..eef564fabd 100644
--- a/packages/skills/skills/remotion/rules/calculate-metadata.md
+++ b/packages/skills/skills/remotion/rules/calculate-metadata.md
@@ -10,19 +10,30 @@ metadata:
Use `calculateMetadata` on a `<Composition>` to dynamically set duration, dimensions, and transform props before rendering.
```tsx
-<Composition id="MyComp" component={MyComponent} durationInFrames={300} fps={30} width={1920} height={1080} defaultProps={{videoSrc: 'https://remotion.media/video.mp4'}} calculateMetadata={calculateMetadata} />
+<Composition
+ id="MyComp"
+ component={MyComponent}
+ durationInFrames={300}
+ fps={30}
+ width={1920}
+ height={1080}
+ defaultProps={{ videoSrc: "https://remotion.media/video.mp4" }}
+ calculateMetadata={calculateMetadata}
+/>
```
## Setting duration based on a video
-Use the `getMediaMetadata()` function from the mediabunny/metadata skill to get the video duration:
+Use the [`getVideoDuration`](./get-video-duration.md) and [`getVideoDimensions`](./get-video-dimensions.md) skills to get the video duration and dimensions:
```tsx
-import {CalculateMetadataFunction} from 'remotion';
-import {getMediaMetadata} from '../get-media-metadata';
+import { CalculateMetadataFunction } from "remotion";
+import { getVideoDuration } from "./get-video-duration";
-const calculateMetadata: CalculateMetadataFunction<Props> = async ({props}) => {
- const {durationInSeconds} = await getMediaMetadata(props.videoSrc);
+const calculateMetadata: CalculateMetadataFunction<Props> = async ({
+ props,
+}) => {
+ const durationInSeconds = await getVideoDuration(props.videoSrc);
return {
durationInFrames: Math.ceil(durationInSeconds * 30),
@@ -32,14 +43,21 @@ const calculateMetadata: CalculateMetadataFunction<Props> = async ({props}) => {
## Matching dimensions of a video
+Use the [`getVideoDimensions`](./get-video-dimensions.md) skill to get the video dimensions:
+
```tsx
-const calculateMetadata: CalculateMetadataFunction<Props> = async ({props}) => {
- const {durationInSeconds, dimensions} = await getMediaMetadata(props.videoSrc);
+import { CalculateMetadataFunction } from "remotion";
+import { getVideoDuration } from "./get-video-duration";
+import { getVideoDimensions } from "./get-video-dimensions";
+
+const calculateMetadata: CalculateMetadataFunction<Props> = async ({
+ props,
+}) => {
+ const dimensions = await getVideoDimensions(props.videoSrc);
return {
- durationInFrames: Math.ceil(durationInSeconds * 30),
- width: dimensions?.width ?? 1920,
- height: dimensions?.height ?? 1080,
+ width: dimensions.width,
+ height: dimensions.height,
};
};
```
@@ -47,11 +65,18 @@ const calculateMetadata: CalculateMetadataFunction<Props> = async ({props}) => {
## Setting duration based on multiple videos
```tsx
-const calculateMetadata: CalculateMetadataFunction<Props> = async ({props}) => {
- const metadataPromises = props.videos.map((video) => getMediaMetadata(video.src));
+const calculateMetadata: CalculateMetadataFunction<Props> = async ({
+ props,
+}) => {
+ const metadataPromises = props.videos.map((video) =>
+ getVideoDuration(video.src),
+ );
const allMetadata = await Promise.all(metadataPromises);
- const totalDuration = allMetadata.reduce((sum, meta) => sum + meta.durationInSeconds, 0);
+ const totalDuration = allMetadata.reduce(
+ (sum, durationInSeconds) => sum + durationInSeconds,
+ 0,
+ );
return {
durationInFrames: Math.ceil(totalDuration * 30),
@@ -64,7 +89,9 @@ const calculateMetadata: CalculateMetadataFunction<Props> = async ({props}) => {
Set the default output filename based on props:
```tsx
-const calculateMetadata: CalculateMetadataFunction<Props> = async ({props}) => {
+const calculateMetadata: CalculateMetadataFunction<Props> = async ({
+ props,
+}) => {
return {
defaultOutName: `video-${props.id}.mp4`,
};
@@ -76,8 +103,11 @@ const calculateMetadata: CalculateMetadataFunction<Props> = async ({props}) => {
Fetch data or transform props before rendering:
```tsx
-const calculateMetadata: CalculateMetadataFunction<Props> = async ({props, abortSignal}) => {
- const response = await fetch(props.dataUrl, {signal: abortSignal});
+const calculateMetadata: CalculateMetadataFunction<Props> = async ({
+ props,
+ abortSignal,
+}) => {
+ const response = await fetch(props.dataUrl, { signal: abortSignal });
const data = await response.json();
return {
diff --git a/packages/skills/skills/remotion/rules/get-audio-duration.md b/packages/skills/skills/remotion/rules/get-audio-duration.md
index fc57d914e6..35ef747174 100644
--- a/packages/skills/skills/remotion/rules/get-audio-duration.md
+++ b/packages/skills/skills/remotion/rules/get-audio-duration.md
@@ -11,7 +11,7 @@ Mediabunny can extract the duration of an audio file. It works in browser, Node.
## Getting audio duration
-```tsx
+```tsx title="get-audio-duration.ts"
import { Input, ALL_FORMATS, UrlSource } from "mediabunny";
export const getAudioDuration = async (src: string) => {
@@ -34,25 +34,25 @@ const duration = await getAudioDuration("https://remotion.media/audio.mp3");
console.log(duration); // e.g. 180.5 (seconds)
```
-## Using with local files
+## Using with staticFile in Remotion
-For local files, use `FileSource` instead of `UrlSource`:
+Make sure to wrap the file path in `staticFile()`:
```tsx
-import { Input, ALL_FORMATS, FileSource } from "mediabunny";
-
-const input = new Input({
- formats: ALL_FORMATS,
- source: new FileSource(file), // File object from input or drag-drop
-});
+import { staticFile } from "remotion";
-const durationInSeconds = await input.computeDuration();
+const duration = await getAudioDuration(staticFile("audio.mp3"));
```
-## Using with staticFile in Remotion
+## In Node.js and Bun
+
+Use `FileSource` instead of `UrlSource`:
```tsx
-import { staticFile } from "remotion";
+import { Input, ALL_FORMATS, FileSource } from "mediabunny";
-const duration = await getAudioDuration(staticFile("audio.mp3"));
+const input = new Input({
+ formats: ALL_FORMATS,
+ source: new FileSource(file), // File object from input or drag-drop
+});
```
diff --git a/packages/skills/skills/remotion/rules/get-video-duration.md b/packages/skills/skills/remotion/rules/get-video-duration.md
index 9236551670..10ab735d16 100644
--- a/packages/skills/skills/remotion/rules/get-video-duration.md
+++ b/packages/skills/skills/remotion/rules/get-video-duration.md
@@ -34,9 +34,19 @@ const duration = await getVideoDuration("https://remotion.media/video.mp4");
console.log(duration); // e.g. 10.5 (seconds)
```
-## Using with local files
+## Video files from the public/ directory
-For local files, use `FileSource` instead of `UrlSource`:
+Make sure to wrap the file path in `staticFile()`:
+
+```tsx
+import { staticFile } from "remotion";
+
+const duration = await getVideoDuration(staticFile("video.mp4"));
+```
+
+## In Node.js and Bun
+
+Use `FileSource` instead of `UrlSource`:
```tsx
import { Input, ALL_FORMATS, FileSource } from "mediabunny";
@@ -48,11 +58,3 @@ const input = new Input({
const durationInSeconds = await input.computeDuration();
```
-
-## Using with staticFile in Remotion
-
-```tsx
-import { staticFile } from "remotion";
-
-const duration = await getVideoDuration(staticFile("video.mp4"));
-```
diff --git a/packages/skills/skills/remotion/rules/measuring-text.md b/packages/skills/skills/remotion/rules/measuring-text.md
index 1bcb33ce73..070a184bea 100644
--- a/packages/skills/skills/remotion/rules/measuring-text.md
+++ b/packages/skills/skills/remotion/rules/measuring-text.md
@@ -12,10 +12,7 @@ metadata:
Install @remotion/layout-utils if it is not already installed:
```bash
-npx remotion add @remotion/layout-utils # If project uses npm
-bunx remotion add @remotion/layout-utils # If project uses bun
-yarn remotion add @remotion/layout-utils # If project uses yarn
-pnpm exec remotion add @remotion/layout-utils # If project uses pnpm
+npx remotion add @remotion/layout-utils
```
## Measuring text dimensions
@@ -104,7 +101,7 @@ waitUntilDone().then(() => {
fontFamily,
fontSize: 32,
});
-})
+});
```
**Use validateFontIsLoaded:** Catch font loading issues early:
diff --git a/packages/skills/skills/remotion/rules/voiceover.md b/packages/skills/skills/remotion/rules/voiceover.md
index b04292cfa6..4de980e7e3 100644
--- a/packages/skills/skills/remotion/rules/voiceover.md
+++ b/packages/skills/skills/remotion/rules/voiceover.md
@@ -7,7 +7,7 @@ metadata:
# Adding AI voiceover to a Remotion composition
-Use ElevenLabs TTS to generate speech audio per scene, then use `calculateMetadata` to dynamically size the composition to match the audio.
+Use ElevenLabs TTS to generate speech audio per scene, then use [`calculateMetadata`](./calculate-metadata) to dynamically size the composition to match the audio.
## Prerequisites
@@ -17,43 +17,21 @@ An **ElevenLabs API key** is required. Store it in a `.env` file at the project
ELEVENLABS_API_KEY=your_key_here
```
-**MUST** ask the user for their ElevenLabs API key if no `.env` file exists or `ELEVENLABS_API_KEY` is not set. **MUST NOT** fall back to other TTS tools (e.g. `say`, `espeak`, Google TTS, or any other provider). ElevenLabs is the only supported voice engine for this workflow.
+**MUST** ask the user for their ElevenLabs API key if no `.env` file exists or `ELEVENLABS_API_KEY` is not set. **MUST NOT** fall back to other TTS tools.
-Install `dotenv` if not already present:
+When running the generation script, use the `--env-file` flag to load the `.env` file:
```bash
-npm install dotenv
+node --env-file=.env --strip-types generate-voiceover.ts
```
-## Defining scene text
-
-Create a JSON config file that maps each scene to its voiceover text. The config can live anywhere in the project β€” a common convention is a `voiceover-configs/` directory.
-
-```json
-{
- "compositionId": "MyComposition",
- "voice": "kPzsL2i3teMYv0FxEYQ6",
- "scenes": [
- { "id": "scene-01-intro", "text": "Welcome to the show." },
- { "id": "scene-02-main", "text": "Here is the main point." },
- { "id": "scene-03-outro", "text": "Thanks for watching." }
- ]
-}
-```
-
-- `compositionId` identifies which composition these scenes belong to.
-- `voice` is an ElevenLabs voice ID. Optional β€” the generation script should define a sensible default.
-- Each scene has a unique `id` (used as the output filename) and `text` to speak.
-
-Conversational phrasing produces more natural-sounding speech than formal writing.
-
## Generating audio with ElevenLabs
Create a script that reads the config, calls the ElevenLabs API for each scene, and writes MP3 files to the `public/` directory so Remotion can access them via `staticFile()`.
The core API call for a single scene:
-```ts
+```ts title="generate-voiceover.ts"
const response = await fetch(
`https://api.elevenlabs.io/v1/text-to-speech/${voiceId}`,
{
@@ -64,7 +42,7 @@ const response = await fetch(
Accept: "audio/mpeg",
},
body: JSON.stringify({
- text: scene.text,
+ text: "Welcome to the show.",
model_id: "eleven_multilingual_v2",
voice_settings: {
stability: 0.5,
@@ -72,113 +50,49 @@ const response = await fetch(
style: 0.3,
},
}),
- }
+ },
);
const audioBuffer = Buffer.from(await response.arrayBuffer());
writeFileSync(`public/voiceover/${compositionId}/${scene.id}.mp3`, audioBuffer);
```
-After writing each MP3, the script **MUST** measure its duration and write a `manifest.json` alongside the audio files:
-
-```json
-{
- "scenes": [
- { "id": "scene-01-intro", "file": "scene-01-intro.mp3", "durationInSeconds": 2.45 },
- { "id": "scene-02-main", "file": "scene-02-main.mp3", "durationInSeconds": 3.12 }
- ]
-}
-```
-
-Use `parseMedia()` from `@remotion/media-parser` to measure each MP3 after writing it:
-
-```ts
-import { parseMedia } from "@remotion/media-parser";
-import { nodeReader } from "@remotion/media-parser/node";
-
-const { durationInSeconds } = await parseMedia({
- src: filepath,
- fields: { durationInSeconds: true },
- reader: nodeReader,
-});
-```
-
-The script **MUST**:
-
-- Load the API key from environment variables β€” never hardcode it.
-- Write output to `public/voiceover/<compositionId>/` so files are available via `staticFile()`.
-- Write a `manifest.json` with per-scene durations so `calculateMetadata` can read them without re-parsing audio at runtime.
-- Add a delay between requests (e.g. 500ms) to respect rate limits.
-- Provide clear error messages when the API key is missing or a request fails.
-
-Add a `package.json` script so it can be run as:
-
-```bash
-npm run generate:voiceover -- <composition-id>
-```
-
-Generated audio files **MUST** be added to `.gitignore`:
-
-```
-public/voiceover/
-```
-
-## Dynamic duration with calculateMetadata
+## Dynamic composition duration with calculateMetadata
-Use `calculateMetadata` to read the manifest and compute the composition length from the pre-measured durations. This ensures scenes are exactly as long as their voiceover requires β€” no runtime audio parsing needed.
+Use [`calculateMetadata`](./calculate-metadata.md) to measure the [audio durations](./get-audio-duration.md) and set the composition length accordingly.
```tsx
import { CalculateMetadataFunction, staticFile } from "remotion";
+import { getAudioDuration } from "./get-audio-duration";
-// Fallback durations (in frames) used when audio files don't exist yet
-const FALLBACK_DURATIONS = [75, 90, 105];
-const AUDIO_PADDING_FRAMES = 12; // breathing room after each clip
const FPS = 30;
-const MANIFEST_PATH = "voiceover/my-comp/manifest.json";
-
const SCENE_AUDIO_FILES = [
"voiceover/my-comp/scene-01-intro.mp3",
"voiceover/my-comp/scene-02-main.mp3",
"voiceover/my-comp/scene-03-outro.mp3",
];
-type Manifest = {
- scenes: { id: string; file: string; durationInSeconds: number }[];
-};
-
export const calculateMetadata: CalculateMetadataFunction<Props> = async ({
props,
}) => {
- try {
- const res = await fetch(staticFile(MANIFEST_PATH));
- const manifest: Manifest = await res.json();
-
- const sceneDurations = manifest.scenes.map((scene, i) => {
- const audioFrames = Math.ceil(scene.durationInSeconds * FPS);
- return Math.max(audioFrames + AUDIO_PADDING_FRAMES, FALLBACK_DURATIONS[i]);
- });
-
- return {
- durationInFrames: sceneDurations.reduce((sum, d) => sum + d, 0),
- props: { ...props, voiceover: { sceneDurations } },
- };
- } catch {
- return {
- durationInFrames: FALLBACK_DURATIONS.reduce((sum, d) => sum + d, 0),
- };
- }
+ const durations = await Promise.all(
+ SCENE_AUDIO_FILES.map((file) => getAudioDuration(staticFile(file))),
+ );
+
+ const sceneDurations = durations.map((durationInSeconds) => {
+ return durationInSeconds * FPS;
+ });
+
+ return {
+ durationInFrames: Math.ceil(sceneDurations.reduce((sum, d) => sum + d, 0)),
+ };
};
```
-Key rules:
+The computed `sceneDurations` are passed into the component via a `voiceover` prop so the component knows how long each scene should be.
-- **MUST** wrap the manifest fetch in `try/catch`. The composition must render without audio files so it works during development before generation.
-- **MUST** define `FALLBACK_DURATIONS` β€” one value per scene. These are the scene lengths used when no audio exists.
-- `AUDIO_PADDING_FRAMES` adds a short pause after each clip before the next scene begins. 12 frames (~0.4s at 30fps) is a good starting point.
-- The computed `sceneDurations` are passed into the component via a `voiceover` prop so the component knows whether audio exists and how long each scene should be.
-
-If the composition uses `<TransitionSeries>`, subtract the overlap from total duration:
+If the composition uses [`<TransitionSeries>`](./transitions.md), subtract the overlap from total duration:
```tsx
const numTransitions = sceneDurations.length - 1;
@@ -189,60 +103,8 @@ const totalFrames =
## Rendering audio in the component
-Add an optional `voiceover` prop to the component schema:
-
-```tsx
-const myCompSchema = z.object({
- // ... other props
- voiceover: z
- .object({ sceneDurations: z.array(z.number()) })
- .optional(),
-});
-```
-
-Use the `voiceover` prop to decide scene lengths and whether to render `<Audio>`:
-
-```tsx
-import { Audio } from "@remotion/media";
-import { staticFile } from "remotion";
-
-export const MyComposition: React.FC<Props> = ({ voiceover }) => {
- const durations = voiceover?.sceneDurations ?? FALLBACK_DURATIONS;
- const hasAudio = !!voiceover;
-
- return (
- <>
- <Sequence durationInFrames={durations[0]}>
- <IntroScene />
- {hasAudio && <Audio src={staticFile(SCENE_AUDIO_FILES[0])} />}
- </Sequence>
- <Sequence from={durations[0]} durationInFrames={durations[1]}>
- <MainScene />
- {hasAudio && <Audio src={staticFile(SCENE_AUDIO_FILES[1])} />}
- </Sequence>
- {/* ... more scenes */}
- </>
- );
-};
-```
-
-**MUST NOT** render `<Audio>` unconditionally β€” the files won't exist until generation runs.
-
-This pattern works with any sequencing approach: `<Sequence>`, `<Series>`, or `<TransitionSeries>`. The core idea is the same β€” use `durations[i]` for each scene's length, and conditionally render `<Audio>` inside each scene.
+See [audio.md](./audio.md) for more information on how to render audio in the component.
## Delaying audio start
-If audio should not start on the first frame of a scene (e.g. to let a visual entrance finish), wrap it in a `<Sequence>`:
-
-```tsx
-<Sequence from={6}>
- <Audio src={staticFile(SCENE_AUDIO_FILES[0])} />
-</Sequence>
-```
-
-## Tuning
-
-- **Silence at end of a scene**: Lower that scene's value in `FALLBACK_DURATIONS` or reduce `AUDIO_PADDING_FRAMES`.
-- **Audio gets cut off**: Increase `AUDIO_PADDING_FRAMES` or that scene's fallback.
-- **Speech sounds robotic**: Rewrite the text conversationally. Short sentences with natural rhythm work best.
-- **Different voice per scene**: Set `"voice"` in the config JSON per-composition, or override via a CLI flag in the generation script.
+See [audio.md#delaying](./audio.md#delaying) for more information on how to delay the audio start.