Skip to content

🎥 Make videos programmatically with React

@remotion/media: Use MediaPlayer for audio-only playback instead of separate AudioPlayer

copilot-swe-agent[bot]2989892d633f
diff --git a/packages/media/src/audio/audio-for-preview.tsx b/packages/media/src/audio/audio-for-preview.tsx
index ced6663726..0ab6214dba 100644
--- a/packages/media/src/audio/audio-for-preview.tsx
+++ b/packages/media/src/audio/audio-for-preview.tsx
@@ -8,7 +8,7 @@ import {
useCurrentFrame,
useVideoConfig,
} from 'remotion';
-import {AudioPlayer} from './audio-player';
+import {MediaPlayer} from '../video/media-player';
const {
useUnsafeVideoConfig,
@@ -68,9 +68,9 @@ const NewAudioForPreview: React.FC<NewAudioForPreviewProps> = ({
}) => {
const videoConfig = useUnsafeVideoConfig();
const frame = useCurrentFrame();
- const audioPlayerRef = useRef<AudioPlayer | null>(null);
+ const mediaPlayerRef = useRef<MediaPlayer | null>(null);
- const [audioPlayerReady, setAudioPlayerReady] = useState(false);
+ const [mediaPlayerReady, setMediaPlayerReady] = useState(false);
const [playing] = Timeline.usePlayingState();
const timelineContext = useContext(Timeline.TimelineContext);
@@ -114,34 +114,34 @@ const NewAudioForPreview: React.FC<NewAudioForPreviewProps> = ({
if (!sharedAudioContext.audioContext) return;
try {
- const player = new AudioPlayer({
+ const player = new MediaPlayer({
src: preloadedSrc,
logLevel,
sharedAudioContext: sharedAudioContext.audioContext,
});
- audioPlayerRef.current = player;
+ mediaPlayerRef.current = player;
player
.initialize(initialTimestamp)
.then(() => {
- setAudioPlayerReady(true);
+ setMediaPlayerReady(true);
Internals.Log.trace(
{logLevel, tag: '@remotion/media'},
- `[NewAudioForPreview] AudioPlayer initialized successfully`,
+ `[NewAudioForPreview] MediaPlayer initialized successfully`,
);
})
.catch((error) => {
Internals.Log.error(
{logLevel, tag: '@remotion/media'},
- '[NewAudioForPreview] Failed to initialize AudioPlayer',
+ '[NewAudioForPreview] Failed to initialize MediaPlayer',
error,
);
});
} catch (error) {
Internals.Log.error(
{logLevel, tag: '@remotion/media'},
- '[NewAudioForPreview] AudioPlayer initialization failed',
+ '[NewAudioForPreview] MediaPlayer initialization failed',
error,
);
}
@@ -152,21 +152,21 @@ const NewAudioForPreview: React.FC<NewAudioForPreviewProps> = ({
delayHandleRef.current = null;
}
- if (audioPlayerRef.current) {
+ if (mediaPlayerRef.current) {
Internals.Log.trace(
{logLevel, tag: '@remotion/media'},
- `[NewAudioForPreview] Disposing AudioPlayer`,
+ `[NewAudioForPreview] Disposing MediaPlayer`,
);
- audioPlayerRef.current.dispose();
- audioPlayerRef.current = null;
+ mediaPlayerRef.current.dispose();
+ mediaPlayerRef.current = null;
}
- setAudioPlayerReady(false);
+ setMediaPlayerReady(false);
};
}, [preloadedSrc, logLevel, sharedAudioContext, initialTimestamp]);
useEffect(() => {
- const audioPlayer = audioPlayerRef.current;
+ const audioPlayer = mediaPlayerRef.current;
if (!audioPlayer) return;
if (playing) {
@@ -180,58 +180,58 @@ const NewAudioForPreview: React.FC<NewAudioForPreviewProps> = ({
} else {
audioPlayer.pause();
}
- }, [playing, logLevel, audioPlayerReady]);
+ }, [playing, logLevel, mediaPlayerReady]);
useEffect(() => {
- const audioPlayer = audioPlayerRef.current;
- if (!audioPlayer || !audioPlayerReady) return;
+ const audioPlayer = mediaPlayerRef.current;
+ if (!audioPlayer || !mediaPlayerReady) return;
audioPlayer.seekTo(currentTime);
Internals.Log.trace(
{logLevel, tag: '@remotion/media'},
`[NewAudioForPreview] Updating target time to ${currentTime.toFixed(3)}s`,
);
- }, [currentTime, logLevel, audioPlayerReady]);
+ }, [currentTime, logLevel, mediaPlayerReady]);
useEffect(() => {
- const audioPlayer = audioPlayerRef.current;
- if (!audioPlayer || !audioPlayerReady) return;
+ const audioPlayer = mediaPlayerRef.current;
+ if (!audioPlayer || !mediaPlayerReady) return;
audioPlayer.onBufferingChange((newBufferingState) => {
if (newBufferingState && !delayHandleRef.current) {
delayHandleRef.current = buffer.delayPlayback();
Internals.Log.trace(
{logLevel, tag: '@remotion/media'},
- '[NewAudioForPreview] AudioPlayer buffering - blocking Remotion playback',
+ '[NewAudioForPreview] MediaPlayer buffering - blocking Remotion playback',
);
} else if (!newBufferingState && delayHandleRef.current) {
delayHandleRef.current.unblock();
delayHandleRef.current = null;
Internals.Log.trace(
{logLevel, tag: '@remotion/media'},
- '[NewAudioForPreview] AudioPlayer unbuffering - unblocking Remotion playback',
+ '[NewAudioForPreview] MediaPlayer unbuffering - unblocking Remotion playback',
);
}
});
- }, [audioPlayerReady, buffer, logLevel]);
+ }, [mediaPlayerReady, buffer, logLevel]);
const effectiveMuted = muted || mediaMuted || userPreferredVolume <= 0;
useEffect(() => {
- const audioPlayer = audioPlayerRef.current;
- if (!audioPlayer || !audioPlayerReady) return;
+ const audioPlayer = mediaPlayerRef.current;
+ if (!audioPlayer || !mediaPlayerReady) return;
audioPlayer.setMuted(effectiveMuted);
- }, [effectiveMuted, audioPlayerReady]);
+ }, [effectiveMuted, mediaPlayerReady]);
useEffect(() => {
- const audioPlayer = audioPlayerRef.current;
- if (!audioPlayer || !audioPlayerReady) {
+ const audioPlayer = mediaPlayerRef.current;
+ if (!audioPlayer || !mediaPlayerReady) {
return;
}
audioPlayer.setVolume(userPreferredVolume);
- }, [userPreferredVolume, audioPlayerReady, logLevel]);
+ }, [userPreferredVolume, mediaPlayerReady, logLevel]);
const effectivePlaybackRate = useMemo(
() => playbackRate * globalPlaybackRate,
@@ -239,8 +239,8 @@ const NewAudioForPreview: React.FC<NewAudioForPreviewProps> = ({
);
useEffect(() => {
- const audioPlayer = audioPlayerRef.current;
- if (!audioPlayer || !audioPlayerReady) {
+ const audioPlayer = mediaPlayerRef.current;
+ if (!audioPlayer || !mediaPlayerReady) {
return;
}
@@ -251,7 +251,7 @@ const NewAudioForPreview: React.FC<NewAudioForPreviewProps> = ({
error,
);
});
- }, [effectivePlaybackRate, audioPlayerReady, logLevel]);
+ }, [effectivePlaybackRate, mediaPlayerReady, logLevel]);
return null;
};
diff --git a/packages/media/src/audio/audio-player.ts b/packages/media/src/audio/audio-player.ts
deleted file mode 100644
index f53426133d..0000000000
--- a/packages/media/src/audio/audio-player.ts
+++ /dev/null
@@ -1,361 +0,0 @@
-import type {WrappedAudioBuffer} from 'mediabunny';
-import {ALL_FORMATS, AudioBufferSink, Input, UrlSource} from 'mediabunny';
-import type {LogLevel} from 'remotion';
-import {Internals} from 'remotion';
-import {sleep, withTimeout} from '../video/timeout-utils';
-
-export const SEEK_THRESHOLD = 0.05;
-
-export class AudioPlayer {
- private src: string;
- private logLevel: LogLevel;
- private playbackRate: number;
-
- private audioSink: AudioBufferSink | null = null;
- private audioBufferIterator: AsyncGenerator<
- WrappedAudioBuffer,
- void,
- unknown
- > | null = null;
-
- private queuedAudioNodes: Set<AudioBufferSourceNode> = new Set();
-
- private gainNode: GainNode | null = null;
-
- private sharedAudioContext: AudioContext;
-
- // audioDelay = mediaTimestamp + audioSyncAnchor - sharedAudioContext.currentTime
- private audioSyncAnchor: number = 0;
-
- private playing = false;
- private muted = false;
-
- private initialized = false;
- private totalDuration = 0;
-
- // for remotion buffer state
- private isBuffering = false;
- private onBufferingChangeCallback?: (isBuffering: boolean) => void;
-
- private readonly HEALTHY_BUFER_THRESHOLD_SECONDS = 1;
-
- constructor({
- src,
- logLevel,
- sharedAudioContext,
- }: {
- src: string;
- logLevel: LogLevel;
- sharedAudioContext: AudioContext;
- }) {
- this.src = src;
- this.logLevel = logLevel ?? 'info';
- this.sharedAudioContext = sharedAudioContext;
- this.playbackRate = 1;
- }
-
- private input: Input<UrlSource> | null = null;
-
- private isReady(): boolean {
- return this.initialized && Boolean(this.sharedAudioContext);
- }
-
- private hasAudio(): boolean {
- return Boolean(this.audioSink && this.sharedAudioContext && this.gainNode);
- }
-
- private isCurrentlyBuffering(): boolean {
- return this.isBuffering && Boolean(this.bufferingStartedAtMs);
- }
-
- public async initialize(startTime: number = 0): Promise<void> {
- try {
- const urlSource = new UrlSource(this.src);
-
- const input = new Input({
- source: urlSource,
- formats: ALL_FORMATS,
- });
-
- this.input = input;
-
- this.totalDuration = await input.computeDuration();
- const audioTrack = await input.getPrimaryAudioTrack();
-
- if (!audioTrack) {
- throw new Error(`No audio track found for ${this.src}`);
- }
-
- if (audioTrack && this.sharedAudioContext) {
- this.audioSink = new AudioBufferSink(audioTrack);
- this.gainNode = this.sharedAudioContext.createGain();
- this.gainNode.connect(this.sharedAudioContext.destination);
- }
-
- if (this.sharedAudioContext) {
- this.audioSyncAnchor = this.sharedAudioContext.currentTime - startTime;
- }
-
- this.initialized = true;
-
- const mediaTime = startTime * this.playbackRate;
- await this.startAudioIterator(mediaTime);
- } catch (error) {
- Internals.Log.error(
- {logLevel: this.logLevel, tag: '@remotion/media'},
- '[AudioPlayer] Failed to initialize',
- error,
- );
- throw error;
- }
- }
-
- private cleanupAudioQueue(): void {
- for (const node of this.queuedAudioNodes) {
- node.stop();
- }
-
- this.queuedAudioNodes.clear();
- }
-
- private async cleanAudioIteratorAndNodes(): Promise<void> {
- await this.audioBufferIterator?.return();
- this.audioBufferIterator = null;
-
- this.cleanupAudioQueue();
- }
-
- public async seekTo(time: number): Promise<void> {
- if (!this.isReady()) return;
-
- const newTime = Math.max(0, Math.min(time, this.totalDuration));
- const currentPlaybackTime = this.getPlaybackTime();
- const isSignificantSeek =
- Math.abs(newTime - currentPlaybackTime) > SEEK_THRESHOLD;
-
- if (isSignificantSeek) {
- this.audioSyncAnchor = this.sharedAudioContext.currentTime - newTime;
-
- if (this.audioSink) {
- await this.cleanAudioIteratorAndNodes();
- }
-
- const mediaTime = newTime * this.playbackRate;
- await this.startAudioIterator(mediaTime);
- }
- }
-
- public async play(): Promise<void> {
- if (!this.isReady()) return;
-
- if (!this.playing) {
- if (this.sharedAudioContext.state === 'suspended') {
- await this.sharedAudioContext.resume();
- }
-
- this.playing = true;
- }
- }
-
- public pause(): void {
- this.playing = false;
- this.cleanupAudioQueue();
- }
-
- public setMuted(muted: boolean): void {
- this.muted = muted;
- if (muted) {
- this.cleanupAudioQueue();
- }
- }
-
- public setVolume(volume: number): void {
- if (!this.gainNode) {
- return;
- }
-
- const appliedVolume = Math.max(0, volume);
- this.gainNode.gain.value = appliedVolume;
- }
-
- public async setPlaybackRate(rate: number): Promise<void> {
- if (this.playbackRate === rate) return;
-
- this.playbackRate = rate;
-
- if (this.hasAudio() && this.playing) {
- const currentPlaybackTime = this.getPlaybackTime();
- const mediaTime = currentPlaybackTime * rate;
-
- await this.cleanAudioIteratorAndNodes();
- await this.startAudioIterator(mediaTime);
- }
- }
-
- public dispose(): void {
- this.input?.dispose();
- this.cleanAudioIteratorAndNodes();
- }
-
- private getPlaybackTime(): number {
- return this.sharedAudioContext.currentTime - this.audioSyncAnchor;
- }
-
- private getAdjustedTimestamp(mediaTimestamp: number): number {
- return mediaTimestamp / this.playbackRate;
- }
-
- private scheduleAudioChunk(
- buffer: AudioBuffer,
- mediaTimestamp: number,
- ): void {
- const adjustedTimestamp = this.getAdjustedTimestamp(mediaTimestamp);
- const targetTime = adjustedTimestamp + this.audioSyncAnchor;
- const delay = targetTime - this.sharedAudioContext.currentTime;
-
- const node = this.sharedAudioContext.createBufferSource();
- node.buffer = buffer;
- node.playbackRate.value = this.playbackRate;
- node.connect(this.gainNode!);
-
- if (delay >= 0) {
- node.start(targetTime);
- } else {
- node.start(this.sharedAudioContext.currentTime, -delay);
- }
-
- this.queuedAudioNodes.add(node);
- node.onended = () => this.queuedAudioNodes.delete(node);
- }
-
- public onBufferingChange(callback: (isBuffering: boolean) => void): void {
- this.onBufferingChangeCallback = callback;
- }
-
- private startAudioIterator = async (timeToSeek: number): Promise<void> => {
- if (!this.hasAudio()) return;
-
- // Clean up existing audio iterator
- await this.audioBufferIterator?.return();
-
- try {
- this.audioBufferIterator = this.audioSink!.buffers(timeToSeek);
- this.runAudioIterator();
- } catch (error) {
- Internals.Log.error(
- {logLevel: this.logLevel, tag: '@remotion/media'},
- '[AudioPlayer] Failed to start audio iterator',
- error,
- );
- }
- };
-
- private bufferingStartedAtMs: number | null = null;
- private minBufferingTimeoutMs: number = 500;
-
- private setBufferingState(isBuffering: boolean): void {
- if (this.isBuffering !== isBuffering) {
- this.isBuffering = isBuffering;
-
- if (isBuffering) {
- this.bufferingStartedAtMs = performance.now();
- this.onBufferingChangeCallback?.(true);
- } else {
- this.bufferingStartedAtMs = null;
- this.onBufferingChangeCallback?.(false);
- }
- }
- }
-
- private maybeResumeFromBuffering(currentBufferDuration: number): void {
- if (!this.isCurrentlyBuffering()) return;
-
- const now = performance.now();
- const bufferingDuration = now - this.bufferingStartedAtMs!;
-
- const minTimeElapsed = bufferingDuration >= this.minBufferingTimeoutMs;
- const bufferHealthy =
- currentBufferDuration >= this.HEALTHY_BUFER_THRESHOLD_SECONDS;
-
- if (minTimeElapsed && bufferHealthy) {
- Internals.Log.trace(
- {logLevel: this.logLevel, tag: '@remotion/media'},
- `[AudioPlayer] Resuming from buffering after ${bufferingDuration}ms - buffer recovered`,
- );
- this.setBufferingState(false);
- }
- }
-
- private runAudioIterator = async (): Promise<void> => {
- if (!this.hasAudio() || !this.audioBufferIterator) return;
-
- try {
- let totalBufferDuration = 0;
- let isFirstBuffer = true;
-
- while (true) {
- const BUFFERING_TIMEOUT_MS = 50;
-
- let result: IteratorResult<WrappedAudioBuffer, void>;
- try {
- result = await withTimeout(
- this.audioBufferIterator.next(),
- BUFFERING_TIMEOUT_MS,
- 'Iterator timeout',
- );
- } catch {
- this.setBufferingState(true);
- await sleep(10);
- continue;
- }
-
- if (result.done || !result.value) {
- break;
- }
-
- const {buffer, timestamp, duration} = result.value;
-
- totalBufferDuration += duration;
-
- this.maybeResumeFromBuffering(totalBufferDuration / this.playbackRate);
-
- if (this.playing && !this.muted) {
- if (isFirstBuffer) {
- this.audioSyncAnchor =
- this.sharedAudioContext.currentTime -
- this.getAdjustedTimestamp(timestamp);
- isFirstBuffer = false;
- }
-
- this.scheduleAudioChunk(buffer, timestamp);
- }
-
- if (
- this.getAdjustedTimestamp(timestamp) - this.getPlaybackTime() >=
- 1
- ) {
- await new Promise<void>((resolve) => {
- const check = () => {
- if (
- this.getAdjustedTimestamp(timestamp) - this.getPlaybackTime() <
- 1
- ) {
- resolve();
- } else {
- setTimeout(check, 10);
- }
- };
-
- check();
- });
- }
- }
- } catch (error) {
- Internals.Log.error(
- {logLevel: this.logLevel, tag: '@remotion/media'},
- '[AudioPlayer] Failed to run audio iterator',
- error,
- );
- }
- };
-}
diff --git a/packages/media/src/audio/audio.tsx b/packages/media/src/audio/audio.tsx
index 448ca21843..d162488b57 100644
--- a/packages/media/src/audio/audio.tsx
+++ b/packages/media/src/audio/audio.tsx
@@ -4,7 +4,8 @@ import {AudioForPreview} from './audio-for-preview';
import {AudioForRendering} from './audio-for-rendering';
import type {AudioProps} from './props';
-const {validateMediaTrimProps, resolveTrimProps, validateMediaProps} = Internals;
+const {validateMediaTrimProps, resolveTrimProps, validateMediaProps} =
+ Internals;
export const Audio: React.FC<AudioProps> = (props) => {
// Should only destruct `trimBefore` and `trimAfter` from props,
@@ -78,11 +79,5 @@ export const Audio: React.FC<AudioProps> = (props) => {
...propsForPreview
} = otherProps;
- return (
- <AudioForPreview
- loop={loop}
- name={name}
- {...propsForPreview}
- />
- );
+ return <AudioForPreview loop={loop} name={name} {...propsForPreview} />;
};
diff --git a/packages/media/src/index.ts b/packages/media/src/index.ts
index e69330b8dd..6d68274091 100644
--- a/packages/media/src/index.ts
+++ b/packages/media/src/index.ts
@@ -10,7 +10,7 @@ export const experimental_Audio = Audio;
*/
export const experimental_Video = Video;
+export {AudioForPreview} from './audio/audio-for-preview';
export {AudioProps, FallbackHtml5AudioProps} from './audio/props';
export {VideoProps} from './video/props';
export {Audio, Video};
-export {AudioForPreview} from './audio/audio-for-preview';
diff --git a/packages/media/src/video/media-player.ts b/packages/media/src/video/media-player.ts
index b25ab70d7d..85b9271a60 100644
--- a/packages/media/src/video/media-player.ts
+++ b/packages/media/src/video/media-player.ts
@@ -13,8 +13,8 @@ import {sleep, withTimeout} from './timeout-utils';
export const SEEK_THRESHOLD = 0.05;
export class MediaPlayer {
- private canvas: HTMLCanvasElement;
- private context: CanvasRenderingContext2D;
+ private canvas: HTMLCanvasElement | null;
+ private context: CanvasRenderingContext2D | null;
private src: string;
private logLevel: LogLevel;
private playbackRate: number;
@@ -69,27 +69,31 @@ export class MediaPlayer {
logLevel,
sharedAudioContext,
}: {
- canvas: HTMLCanvasElement;
+ canvas?: HTMLCanvasElement;
src: string;
logLevel: LogLevel;
sharedAudioContext: AudioContext;
}) {
- this.canvas = canvas;
+ this.canvas = canvas ?? null;
this.src = src;
this.logLevel = logLevel ?? 'info';
this.sharedAudioContext = sharedAudioContext;
this.playbackRate = 1;
- const context = canvas.getContext('2d', {
- alpha: false,
- desynchronized: true,
- });
+ if (canvas) {
+ const context = canvas.getContext('2d', {
+ alpha: false,
+ desynchronized: true,
+ });
- if (!context) {
- throw new Error('Could not get 2D context from canvas');
- }
+ if (!context) {
+ throw new Error('Could not get 2D context from canvas');
+ }
- this.context = context;
+ this.context = context;
+ } else {
+ this.context = null;
+ }
}
private input: Input<UrlSource> | null = null;
@@ -125,7 +129,7 @@ export class MediaPlayer {
throw new Error(`No video or audio track found for ${this.src}`);
}
- if (videoTrack) {
+ if (videoTrack && this.canvas && this.context) {
this.canvasSink = new CanvasSink(videoTrack, {
poolSize: 2,
fit: 'contain',
@@ -302,7 +306,7 @@ export class MediaPlayer {
public onVideoFrame(callback: (frame: CanvasImageSource) => void): void {
this.onVideoFrameCallback = callback;
- if (this.initialized && callback) {
+ if (this.initialized && callback && this.canvas) {
callback(this.canvas);
}
}
@@ -357,9 +361,11 @@ export class MediaPlayer {
}
private drawCurrentFrame(): void {
- this.context.drawImage(this.nextFrame!.canvas, 0, 0);
+ if (this.context && this.nextFrame) {
+ this.context.drawImage(this.nextFrame.canvas, 0, 0);
+ }
- if (this.onVideoFrameCallback) {
+ if (this.onVideoFrameCallback && this.canvas) {
this.onVideoFrameCallback(this.canvas);
}
@@ -407,14 +413,14 @@ export class MediaPlayer {
return;
}
- if (firstFrame) {
+ if (firstFrame && this.context) {
Internals.Log.trace(
{logLevel: this.logLevel, tag: '@remotion/media'},
`[MediaPlayer] Drew initial frame ${firstFrame.timestamp.toFixed(3)}s`,
);
this.context.drawImage(firstFrame.canvas, 0, 0);
- if (this.onVideoFrameCallback) {
+ if (this.onVideoFrameCallback && this.canvas) {
this.onVideoFrameCallback(this.canvas);
}
}