Skip to content

🎥 Make videos programmatically with React

add an audio tag as well

Jonny Burgere92e05e3dee9
diff --git a/packages/core/src/internals.ts b/packages/core/src/internals.ts
index 2a4b4fd293..923f79cbf9 100644
--- a/packages/core/src/internals.ts
+++ b/packages/core/src/internals.ts
@@ -1,5 +1,6 @@
import {createRef} from 'react';
import {getAbsoluteSrc} from './absolute-src.js';
+import {AudioForPreview} from './audio/AudioForPreview.js';
import {
SharedAudioContext,
SharedAudioContextProvider,
@@ -207,6 +208,7 @@ export const Internals = {
compositionSelectorRef,
RemotionEnvironmentContext,
warnAboutTooHighVolume,
+ AudioForPreview,
} as const;
export type {
diff --git a/packages/media/src/audio/audio-for-rendering.tsx b/packages/media/src/audio/audio-for-rendering.tsx
new file mode 100644
index 0000000000..28323df668
--- /dev/null
+++ b/packages/media/src/audio/audio-for-rendering.tsx
@@ -0,0 +1,134 @@
+import type React from 'react';
+import {useContext, useLayoutEffect, useMemo, useState} from 'react';
+import {
+ cancelRender,
+ Internals,
+ useCurrentFrame,
+ useDelayRender,
+ useRemotionEnvironment,
+} from 'remotion';
+import {extractFrameViaBroadcastChannel} from '../extract-frame-via-broadcast-channel';
+import type {AudioProps} from './props';
+
+export const AudioForRendering: React.FC<AudioProps> = ({
+ volume: volumeProp,
+ playbackRate,
+ src,
+ muted,
+ loopVolumeCurveBehavior,
+ delayRenderRetries,
+ delayRenderTimeoutInMilliseconds,
+ logLevel = window.remotion_logLevel,
+}) => {
+ const absoluteFrame = Internals.useTimelinePosition();
+ const videoConfig = Internals.useUnsafeVideoConfig();
+ const {registerRenderAsset, unregisterRenderAsset} = useContext(
+ Internals.RenderAssetManager,
+ );
+ const frame = useCurrentFrame();
+ const volumePropsFrame = Internals.useFrameForVolumeProp(
+ loopVolumeCurveBehavior ?? 'repeat',
+ );
+ const environment = useRemotionEnvironment();
+
+ const [id] = useState(() => `${Math.random()}`.replace('0.', ''));
+
+ if (!videoConfig) {
+ throw new Error('No video config found');
+ }
+
+ if (!src) {
+ throw new TypeError('No `src` was passed to <Audio>.');
+ }
+
+ const volume = Internals.evaluateVolume({
+ volume: volumeProp,
+ frame: volumePropsFrame,
+ mediaVolume: 1,
+ });
+
+ Internals.warnAboutTooHighVolume(volume);
+
+ const shouldRenderAudio = useMemo(() => {
+ if (!window.remotion_audioEnabled) {
+ return false;
+ }
+
+ if (muted) {
+ return false;
+ }
+
+ if (volume <= 0) {
+ return false;
+ }
+
+ return true;
+ }, [muted, volume]);
+
+ const {fps} = videoConfig;
+
+ const {delayRender, continueRender} = useDelayRender();
+
+ useLayoutEffect(() => {
+ const actualFps = playbackRate ? fps / playbackRate : fps;
+ const timestamp = frame / actualFps;
+ const durationInSeconds = 1 / actualFps;
+
+ const newHandle = delayRender(`Extracting audio for frame ${frame}`, {
+ retries: delayRenderRetries ?? undefined,
+ timeoutInMilliseconds: delayRenderTimeoutInMilliseconds ?? undefined,
+ });
+
+ extractFrameViaBroadcastChannel({
+ src,
+ timeInSeconds: timestamp,
+ durationInSeconds,
+ logLevel: logLevel ?? 'info',
+ includeAudio: shouldRenderAudio,
+ includeVideo: false,
+ isClientSideRendering: environment.isClientSideRendering,
+ })
+ .then(({audio}) => {
+ if (audio) {
+ registerRenderAsset({
+ type: 'inline-audio',
+ id,
+ audio: Array.from(audio.data),
+ sampleRate: audio.sampleRate,
+ numberOfChannels: audio.numberOfChannels,
+ frame: absoluteFrame,
+ timestamp: audio.timestamp,
+ duration: (audio.numberOfFrames / audio.sampleRate) * 1_000_000,
+ });
+ }
+
+ continueRender(newHandle);
+ })
+ .catch((error) => {
+ cancelRender(error);
+ });
+
+ return () => {
+ continueRender(newHandle);
+ unregisterRenderAsset(id);
+ };
+ }, [
+ absoluteFrame,
+ continueRender,
+ delayRender,
+ delayRenderRetries,
+ delayRenderTimeoutInMilliseconds,
+ environment.isClientSideRendering,
+ fps,
+ frame,
+ id,
+ logLevel,
+ playbackRate,
+ registerRenderAsset,
+ shouldRenderAudio,
+ src,
+ unregisterRenderAsset,
+ ]);
+
+ return null;
+};
diff --git a/packages/media/src/audio/audio.tsx b/packages/media/src/audio/audio.tsx
new file mode 100644
index 0000000000..7f8a424ad6
--- /dev/null
+++ b/packages/media/src/audio/audio.tsx
@@ -0,0 +1,138 @@
+import React, {useCallback, useContext} from 'react';
+import {
+ cancelRender,
+ Internals,
+ Sequence,
+ useRemotionEnvironment,
+} from 'remotion';
+import {SharedAudioContext} from '../../../core/src/audio/shared-audio-tags';
+import {AudioForRendering} from './audio-for-rendering';
+import type {AudioProps} from './props';
+
+const {
+ validateMediaTrimProps,
+ resolveTrimProps,
+ validateMediaProps,
+ AudioForPreview,
+} = Internals;
+
+export const Audio: React.FC<AudioProps> = (props) => {
+ const audioContext = useContext(SharedAudioContext);
+
+ // Should only destruct `trimBefore` and `trimAfter` from props,
+ // rest gets drilled down
+ const {
+ trimBefore,
+ trimAfter,
+ name,
+ pauseWhenBuffering,
+ stack,
+ showInTimeline,
+ onError: onRemotionError,
+ loop,
+ ...otherProps
+ } = props;
+ const environment = useRemotionEnvironment();
+
+ const onDuration = useCallback(() => undefined, []);
+
+ if (typeof props.src !== 'string') {
+ throw new TypeError(
+ `The \`<Audio>\` tag requires a string for \`src\`, but got ${JSON.stringify(
+ props.src,
+ )} instead.`,
+ );
+ }
+
+ validateMediaTrimProps({
+ startFrom: undefined,
+ endAt: undefined,
+ trimBefore,
+ trimAfter,
+ });
+
+ const {trimBeforeValue, trimAfterValue} = resolveTrimProps({
+ startFrom: undefined,
+ endAt: undefined,
+ trimBefore,
+ trimAfter,
+ });
+
+ const onError: React.ReactEventHandler<HTMLAudioElement> = useCallback(
+ (e) => {
+ // eslint-disable-next-line no-console
+ console.log(e.currentTarget.error);
+
+ // If there is no `loop` property, we don't need to get the duration
+ // and this does not need to be a fatal error
+ const errMessage = `Could not play audio: ${e.currentTarget.error}. See https://remotion.dev/docs/media-playback-error for help.`;
+
+ if (loop) {
+ if (onRemotionError) {
+ onRemotionError(new Error(errMessage));
+ return;
+ }
+
+ cancelRender(new Error(errMessage));
+ } else {
+ onRemotionError?.(new Error(errMessage));
+ // eslint-disable-next-line no-console
+ console.warn(errMessage);
+ }
+ },
+ [onRemotionError, loop],
+ );
+
+ if (
+ typeof trimBeforeValue !== 'undefined' ||
+ typeof trimAfterValue !== 'undefined'
+ ) {
+ return (
+ <Sequence
+ layout="none"
+ from={0 - (trimBeforeValue ?? 0)}
+ showInTimeline={false}
+ durationInFrames={trimAfterValue}
+ name={name}
+ >
+ <Audio
+ pauseWhenBuffering={pauseWhenBuffering ?? false}
+ {...otherProps}
+ />
+ </Sequence>
+ );
+ }
+
+ validateMediaProps(props, 'Video');
+
+ if (environment.isRendering) {
+ return <AudioForRendering {...otherProps} />;
+ }
+
+ const {
+ onAutoPlayError,
+ crossOrigin,
+ delayRenderRetries,
+ delayRenderTimeoutInMilliseconds,
+ ...propsForPreview
+ } = otherProps;
+
+ return (
+ <AudioForPreview
+ _remotionInternalNativeLoopPassed={
+ props._remotionInternalNativeLoopPassed ?? false
+ }
+ _remotionInternalStack={stack ?? null}
+ shouldPreMountAudioTags={
+ audioContext !== null && audioContext.numberOfAudioTags > 0
+ }
+ {...propsForPreview}
+ onNativeError={onError}
+ onDuration={onDuration}
+ // Proposal: Make this default to true in v5
+ pauseWhenBuffering={pauseWhenBuffering ?? false}
+ _remotionInternalNeedsDurationCalculation={Boolean(loop)}
+ showInTimeline={showInTimeline ?? true}
+ />
+ );
+};
diff --git a/packages/media/src/audio/props.ts b/packages/media/src/audio/props.ts
new file mode 100644
index 0000000000..147c450b1e
--- /dev/null
+++ b/packages/media/src/audio/props.ts
@@ -0,0 +1,30 @@
+import type {LoopVolumeCurveBehavior, VolumeProp} from 'remotion';
+import type {LogLevel} from '../log';
+
+export type AudioProps = {
+ src: string;
+ trimBefore?: number;
+ trimAfter?: number;
+ volume?: VolumeProp;
+ loopVolumeCurveBehavior?: LoopVolumeCurveBehavior;
+ name?: string;
+ pauseWhenBuffering?: boolean;
+ showInTimeline?: boolean;
+ onAutoPlayError?: null | (() => void);
+ playbackRate?: number;
+ muted?: boolean;
+ delayRenderRetries?: number;
+ delayRenderTimeoutInMilliseconds?: number;
+ crossOrigin?: '' | 'anonymous' | 'use-credentials';
+ style?: React.CSSProperties;
+ onError?: (err: Error) => void;
+ useWebAudioApi?: boolean;
+ acceptableTimeShiftInSeconds?: number;
+ /**
+ * @deprecated For internal use only
+ */
+ stack?: string;
+ logLevel?: LogLevel;
+ loop?: boolean;
+ _remotionInternalNativeLoopPassed?: boolean;
+};
diff --git a/packages/media/src/extract-frame-via-broadcast-channel.ts b/packages/media/src/extract-frame-via-broadcast-channel.ts
index 25d4616b39..cbf421a0f7 100644
--- a/packages/media/src/extract-frame-via-broadcast-channel.ts
+++ b/packages/media/src/extract-frame-via-broadcast-channel.ts
@@ -9,7 +9,8 @@ type ExtractFrameRequest = {
durationInSeconds: number;
id: string;
logLevel: LogLevel;
- shouldRenderAudio: boolean;
+ includeAudio: boolean;
+ includeVideo: boolean;
};
type ExtractFrameResponse =
@@ -38,7 +39,8 @@ if (window.remotion_broadcastChannel && window.remotion_isMainTab) {
timeInSeconds: data.timeInSeconds,
logLevel: data.logLevel,
durationInSeconds: data.durationInSeconds,
- includeAudio: data.shouldRenderAudio,
+ includeAudio: data.includeAudio,
+ includeVideo: data.includeVideo,
});
const videoFrame = frame;
@@ -79,14 +81,16 @@ export const extractFrameViaBroadcastChannel = async ({
timeInSeconds,
logLevel,
durationInSeconds,
- shouldRenderAudio,
+ includeAudio,
+ includeVideo,
isClientSideRendering,
}: {
src: string;
timeInSeconds: number;
durationInSeconds: number;
logLevel: LogLevel;
- shouldRenderAudio: boolean;
+ includeAudio: boolean;
+ includeVideo: boolean;
isClientSideRendering: boolean;
}): Promise<{
frame: ImageBitmap | VideoFrame | null;
@@ -98,7 +102,8 @@ export const extractFrameViaBroadcastChannel = async ({
src,
timeInSeconds,
durationInSeconds,
- includeAudio: shouldRenderAudio,
+ includeAudio,
+ includeVideo,
});
return {
@@ -152,7 +157,8 @@ export const extractFrameViaBroadcastChannel = async ({
id: requestId,
logLevel,
durationInSeconds,
- shouldRenderAudio,
+ includeAudio,
+ includeVideo,
};
window.remotion_broadcastChannel!.postMessage(request);
diff --git a/packages/media/src/extract-frame.ts b/packages/media/src/extract-frame.ts
index 006870d57d..c18fc07f92 100644
--- a/packages/media/src/extract-frame.ts
+++ b/packages/media/src/extract-frame.ts
@@ -183,22 +183,26 @@ export const extractFrameAndAudio = async ({
logLevel,
durationInSeconds,
includeAudio,
+ includeVideo,
}: {
src: string;
timeInSeconds: number;
logLevel: LogLevel;
durationInSeconds: number;
includeAudio: boolean;
+ includeVideo: boolean;
}): Promise<{
frame: VideoFrame | null;
audio: PcmS16AudioData | null;
}> => {
const [frame, audio] = await Promise.all([
- extractFrame({
- src,
- timeInSeconds,
- logLevel,
- }),
+ includeVideo
+ ? extractFrame({
+ src,
+ timeInSeconds,
+ logLevel,
+ })
+ : null,
includeAudio
? extractAudio({
src,
diff --git a/packages/media/src/index.ts b/packages/media/src/index.ts
index 9a56a2a591..6bd9a94512 100644
--- a/packages/media/src/index.ts
+++ b/packages/media/src/index.ts
@@ -1 +1,4 @@
-export {Video as experimental_Video} from './video';
+export {Audio as experimental_Audio} from './audio/audio';
+export {AudioProps} from './audio/props';
+export {VideoProps} from './video/props';
+export {Video as experimental_Video} from './video/video';
diff --git a/packages/media/src/test/browser.test.ts b/packages/media/src/test/browser.test.ts
index b76f24ce4f..dd0c49c861 100644
--- a/packages/media/src/test/browser.test.ts
+++ b/packages/media/src/test/browser.test.ts
@@ -10,6 +10,7 @@ test('Should be able to extract a frame', async () => {
durationInSeconds: 1 / 30,
logLevel: 'info',
includeAudio: true,
+ includeVideo: true,
});
assert(frame);
@@ -38,6 +39,7 @@ test('Should manage the cache', async () => {
durationInSeconds: 1 / 30,
logLevel: 'verbose',
includeAudio: true,
+ includeVideo: true,
});
}
diff --git a/packages/media/src/props.ts b/packages/media/src/video/props.ts
similarity index 85%
rename from packages/media/src/props.ts
rename to packages/media/src/video/props.ts
index 58729e19f5..5e9639f53d 100644
--- a/packages/media/src/props.ts
+++ b/packages/media/src/video/props.ts
@@ -1,5 +1,9 @@
-import type {LoopVolumeCurveBehavior, OnVideoFrame, VolumeProp} from 'remotion';
-import type {LogLevel} from './log';
+import type {
+ LogLevel,
+ LoopVolumeCurveBehavior,
+ OnVideoFrame,
+ VolumeProp,
+} from 'remotion';
export type VideoProps = {
src: string;
diff --git a/packages/media/src/video-for-rendering.tsx b/packages/media/src/video/video-for-rendering.tsx
similarity index 95%
rename from packages/media/src/video-for-rendering.tsx
rename to packages/media/src/video/video-for-rendering.tsx
index 6851d809a2..f58592c206 100644
--- a/packages/media/src/video-for-rendering.tsx
+++ b/packages/media/src/video/video-for-rendering.tsx
@@ -12,7 +12,7 @@ import {
useDelayRender,
useRemotionEnvironment,
} from 'remotion';
-import {extractFrameViaBroadcastChannel} from './extract-frame-via-broadcast-channel';
+import {extractFrameViaBroadcastChannel} from '../extract-frame-via-broadcast-channel';
import type {VideoProps} from './props';
export const VideoForRendering: React.FC<VideoProps> = ({
@@ -96,7 +96,8 @@ export const VideoForRendering: React.FC<VideoProps> = ({
timeInSeconds: timestamp,
durationInSeconds,
logLevel: logLevel ?? 'info',
- shouldRenderAudio,
+ includeAudio: shouldRenderAudio,
+ includeVideo: true,
isClientSideRendering: environment.isClientSideRendering,
})
.then(({frame: imageBitmap, audio}) => {
diff --git a/packages/media/src/video.tsx b/packages/media/src/video/video.tsx
similarity index 96%
rename from packages/media/src/video.tsx
rename to packages/media/src/video/video.tsx
index 250a35158b..2d79a1da27 100644
--- a/packages/media/src/video.tsx
+++ b/packages/media/src/video/video.tsx
@@ -11,7 +11,7 @@ const {
} = Internals;
export const Video: React.FC<VideoProps> = (props) => {
- // Should only destruct `startFrom` and `endAt` from props,
+ // Should only destruct `trimBefore` and `trimAfter` from props,
// rest gets drilled down
const {
trimBefore,
diff --git a/packages/media/vitest.config.ts b/packages/media/vitest.config.ts
index af34244aa4..b262673b08 100644
--- a/packages/media/vitest.config.ts
+++ b/packages/media/vitest.config.ts
@@ -7,6 +7,7 @@ export default defineConfig({
provider: 'webdriverio',
instances: [{browser: 'chrome'}],
headless: true,
+ screenshotFailures: false,
},
},
publicDir: path.join(__dirname, '..', 'example-videos', 'videos'),