Skip to content

🎥 Make videos programmatically with React

@remotion/media: Create AudioPlayer and AudioForPreview with mediabunny

copilot-swe-agent[bot]24862f0c3905
diff --git a/packages/media/src/audio/audio-for-preview.tsx b/packages/media/src/audio/audio-for-preview.tsx
new file mode 100644
index 0000000000..ced6663726
--- /dev/null
+++ b/packages/media/src/audio/audio-for-preview.tsx
@@ -0,0 +1,445 @@
+import {ALL_FORMATS, Input, UrlSource} from 'mediabunny';
+import React, {useContext, useEffect, useMemo, useRef, useState} from 'react';
+import type {LogLevel, LoopVolumeCurveBehavior, VolumeProp} from 'remotion';
+import {
+ Internals,
+ Loop,
+ useBufferState,
+ useCurrentFrame,
+ useVideoConfig,
+} from 'remotion';
+import {AudioPlayer} from './audio-player';
+
+const {
+ useUnsafeVideoConfig,
+ Timeline,
+ SharedAudioContext,
+ useMediaMutedState,
+ useMediaVolumeState,
+ useFrameForVolumeProp,
+ evaluateVolume,
+ warnAboutTooHighVolume,
+ usePreload,
+ useLogLevel,
+} = Internals;
+
+const calculateLoopDuration = ({
+ endAt,
+ mediaDuration,
+ playbackRate,
+ startFrom,
+}: {
+ mediaDuration: number;
+ playbackRate: number;
+ startFrom: number | undefined;
+ endAt: number | undefined;
+}) => {
+ let duration = mediaDuration;
+
+ if (typeof endAt !== 'undefined') {
+ duration = endAt;
+ }
+
+ if (typeof startFrom !== 'undefined') {
+ duration -= startFrom;
+ }
+
+ const actualDuration = duration / playbackRate;
+
+ return Math.floor(actualDuration);
+};
+
+type NewAudioForPreviewProps = {
+ readonly src: string;
+ readonly playbackRate: number;
+ readonly logLevel: LogLevel;
+ readonly muted: boolean;
+ readonly volume: VolumeProp;
+ readonly loopVolumeCurveBehavior: LoopVolumeCurveBehavior;
+};
+
+const NewAudioForPreview: React.FC<NewAudioForPreviewProps> = ({
+ src,
+ playbackRate,
+ logLevel,
+ muted,
+ volume,
+ loopVolumeCurveBehavior,
+}) => {
+ const videoConfig = useUnsafeVideoConfig();
+ const frame = useCurrentFrame();
+ const audioPlayerRef = useRef<AudioPlayer | null>(null);
+
+ const [audioPlayerReady, setAudioPlayerReady] = useState(false);
+
+ const [playing] = Timeline.usePlayingState();
+ const timelineContext = useContext(Timeline.TimelineContext);
+ const globalPlaybackRate = timelineContext.playbackRate;
+ const sharedAudioContext = useContext(SharedAudioContext);
+ const buffer = useBufferState();
+ const delayHandleRef = useRef<{unblock: () => void} | null>(null);
+
+ const [mediaMuted] = useMediaMutedState();
+ const [mediaVolume] = useMediaVolumeState();
+
+ const volumePropFrame = useFrameForVolumeProp(
+ loopVolumeCurveBehavior ?? 'repeat',
+ );
+
+ const userPreferredVolume = evaluateVolume({
+ frame: volumePropFrame,
+ volume,
+ mediaVolume,
+ });
+
+ warnAboutTooHighVolume(userPreferredVolume);
+
+ if (!videoConfig) {
+ throw new Error('No video config found');
+ }
+
+ if (!src) {
+ throw new TypeError('No `src` was passed to <NewAudioForPreview>.');
+ }
+
+ const actualFps = videoConfig.fps / playbackRate;
+ const currentTime = frame / actualFps;
+
+ const [initialTimestamp] = useState(currentTime);
+
+ const preloadedSrc = usePreload(src);
+
+ useEffect(() => {
+ if (!sharedAudioContext) return;
+ if (!sharedAudioContext.audioContext) return;
+
+ try {
+ const player = new AudioPlayer({
+ src: preloadedSrc,
+ logLevel,
+ sharedAudioContext: sharedAudioContext.audioContext,
+ });
+
+ audioPlayerRef.current = player;
+
+ player
+ .initialize(initialTimestamp)
+ .then(() => {
+ setAudioPlayerReady(true);
+ Internals.Log.trace(
+ {logLevel, tag: '@remotion/media'},
+ `[NewAudioForPreview] AudioPlayer initialized successfully`,
+ );
+ })
+ .catch((error) => {
+ Internals.Log.error(
+ {logLevel, tag: '@remotion/media'},
+ '[NewAudioForPreview] Failed to initialize AudioPlayer',
+ error,
+ );
+ });
+ } catch (error) {
+ Internals.Log.error(
+ {logLevel, tag: '@remotion/media'},
+ '[NewAudioForPreview] AudioPlayer initialization failed',
+ error,
+ );
+ }
+
+ return () => {
+ if (delayHandleRef.current) {
+ delayHandleRef.current.unblock();
+ delayHandleRef.current = null;
+ }
+
+ if (audioPlayerRef.current) {
+ Internals.Log.trace(
+ {logLevel, tag: '@remotion/media'},
+ `[NewAudioForPreview] Disposing AudioPlayer`,
+ );
+ audioPlayerRef.current.dispose();
+ audioPlayerRef.current = null;
+ }
+
+ setAudioPlayerReady(false);
+ };
+ }, [preloadedSrc, logLevel, sharedAudioContext, initialTimestamp]);
+
+ useEffect(() => {
+ const audioPlayer = audioPlayerRef.current;
+ if (!audioPlayer) return;
+
+ if (playing) {
+ audioPlayer.play().catch((error) => {
+ Internals.Log.error(
+ {logLevel, tag: '@remotion/media'},
+ '[NewAudioForPreview] Failed to play',
+ error,
+ );
+ });
+ } else {
+ audioPlayer.pause();
+ }
+ }, [playing, logLevel, audioPlayerReady]);
+
+ useEffect(() => {
+ const audioPlayer = audioPlayerRef.current;
+ if (!audioPlayer || !audioPlayerReady) return;
+
+ audioPlayer.seekTo(currentTime);
+ Internals.Log.trace(
+ {logLevel, tag: '@remotion/media'},
+ `[NewAudioForPreview] Updating target time to ${currentTime.toFixed(3)}s`,
+ );
+ }, [currentTime, logLevel, audioPlayerReady]);
+
+ useEffect(() => {
+ const audioPlayer = audioPlayerRef.current;
+ if (!audioPlayer || !audioPlayerReady) 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',
+ );
+ } else if (!newBufferingState && delayHandleRef.current) {
+ delayHandleRef.current.unblock();
+ delayHandleRef.current = null;
+ Internals.Log.trace(
+ {logLevel, tag: '@remotion/media'},
+ '[NewAudioForPreview] AudioPlayer unbuffering - unblocking Remotion playback',
+ );
+ }
+ });
+ }, [audioPlayerReady, buffer, logLevel]);
+
+ const effectiveMuted = muted || mediaMuted || userPreferredVolume <= 0;
+
+ useEffect(() => {
+ const audioPlayer = audioPlayerRef.current;
+ if (!audioPlayer || !audioPlayerReady) return;
+
+ audioPlayer.setMuted(effectiveMuted);
+ }, [effectiveMuted, audioPlayerReady]);
+
+ useEffect(() => {
+ const audioPlayer = audioPlayerRef.current;
+ if (!audioPlayer || !audioPlayerReady) {
+ return;
+ }
+
+ audioPlayer.setVolume(userPreferredVolume);
+ }, [userPreferredVolume, audioPlayerReady, logLevel]);
+
+ const effectivePlaybackRate = useMemo(
+ () => playbackRate * globalPlaybackRate,
+ [playbackRate, globalPlaybackRate],
+ );
+
+ useEffect(() => {
+ const audioPlayer = audioPlayerRef.current;
+ if (!audioPlayer || !audioPlayerReady) {
+ return;
+ }
+
+ audioPlayer.setPlaybackRate(effectivePlaybackRate).catch((error) => {
+ Internals.Log.error(
+ {logLevel, tag: '@remotion/media'},
+ '[NewAudioForPreview] Failed to set playback rate',
+ error,
+ );
+ });
+ }, [effectivePlaybackRate, audioPlayerReady, logLevel]);
+
+ return null;
+};
+
+interface AudioForPreviewWithDurationProps {
+ readonly durationInSeconds: number | null;
+ readonly src: string;
+ readonly playbackRate: number;
+ readonly logLevel: LogLevel;
+ readonly muted: boolean;
+ readonly volume: VolumeProp;
+ readonly loopVolumeCurveBehavior: LoopVolumeCurveBehavior;
+ readonly loop: boolean;
+ readonly name: string | undefined;
+ readonly trimAfter: number | undefined;
+ readonly trimBefore: number | undefined;
+}
+
+const AudioForPreviewWithDuration: React.FC<
+ AudioForPreviewWithDurationProps
+> = ({
+ durationInSeconds,
+ logLevel,
+ loopVolumeCurveBehavior,
+ muted,
+ playbackRate,
+ src,
+ volume,
+ loop,
+ name,
+ trimAfter,
+ trimBefore,
+}) => {
+ const {fps} = useVideoConfig();
+
+ if (loop) {
+ if (!Number.isFinite(durationInSeconds) || durationInSeconds === null) {
+ return (
+ <AudioForPreviewWithDuration
+ loop={false}
+ durationInSeconds={durationInSeconds}
+ logLevel={logLevel}
+ loopVolumeCurveBehavior={loopVolumeCurveBehavior}
+ muted={muted}
+ playbackRate={playbackRate}
+ src={src}
+ volume={volume}
+ name={name}
+ trimAfter={trimAfter}
+ trimBefore={trimBefore}
+ />
+ );
+ }
+
+ const mediaDuration = durationInSeconds * fps;
+
+ return (
+ <Loop
+ durationInFrames={calculateLoopDuration({
+ endAt: trimAfter,
+ mediaDuration,
+ playbackRate: playbackRate ?? 1,
+ startFrom: trimBefore,
+ })}
+ layout="none"
+ name={name}
+ >
+ <AudioForPreviewWithDuration
+ loop={false}
+ durationInSeconds={durationInSeconds}
+ logLevel={logLevel}
+ loopVolumeCurveBehavior={loopVolumeCurveBehavior}
+ muted={muted}
+ playbackRate={playbackRate}
+ src={src}
+ volume={volume}
+ name={name}
+ trimAfter={trimAfter}
+ trimBefore={trimBefore}
+ />
+ </Loop>
+ );
+ }
+
+ return (
+ <NewAudioForPreview
+ src={src}
+ playbackRate={playbackRate}
+ logLevel={logLevel}
+ muted={muted}
+ volume={volume}
+ loopVolumeCurveBehavior={loopVolumeCurveBehavior}
+ />
+ );
+};
+
+type InnerAudioProps = {
+ readonly loop?: boolean;
+ readonly src: string;
+ readonly logLevel?: LogLevel;
+ readonly muted?: boolean;
+ readonly name?: string | undefined;
+ readonly volume?: VolumeProp;
+ readonly loopVolumeCurveBehavior?: LoopVolumeCurveBehavior;
+ readonly playbackRate?: number;
+ // Props we ignore but are passed from old usage
+ readonly _remotionInternalNativeLoopPassed?: boolean;
+ readonly _remotionInternalStack?: string | null;
+ readonly shouldPreMountAudioTags?: boolean;
+ readonly onNativeError?: React.ReactEventHandler<HTMLAudioElement>;
+ readonly onDuration?: (src: string, durationInSeconds: number) => void;
+ readonly pauseWhenBuffering?: boolean;
+ readonly _remotionInternalNeedsDurationCalculation?: boolean;
+ readonly showInTimeline?: boolean;
+};
+
+export const AudioForPreview: React.FC<InnerAudioProps> = ({
+ loop = false,
+ src,
+ logLevel: logLevelProp,
+ muted = false,
+ name,
+ volume = 1,
+ loopVolumeCurveBehavior = 'repeat',
+ playbackRate = 1,
+}) => {
+ const logLevel = useLogLevel() ?? logLevelProp ?? 'info';
+ const preloadedSrc = usePreload(src);
+
+ const [durationInSeconds, setDurationInSeconds] = useState<number | null>(
+ null,
+ );
+
+ useEffect(() => {
+ if (!loop) {
+ return;
+ }
+
+ let cancelled = false;
+
+ const computeDuration = async () => {
+ const urlSource = new UrlSource(preloadedSrc);
+ const input = new Input({
+ source: urlSource,
+ formats: ALL_FORMATS,
+ });
+
+ try {
+ const duration = await input.computeDuration();
+
+ if (!cancelled) {
+ setDurationInSeconds(duration);
+ }
+ } catch (error) {
+ Internals.Log.error(
+ {logLevel, tag: '@remotion/media'},
+ '[AudioForPreview] Failed to compute duration',
+ error,
+ );
+ } finally {
+ input.dispose();
+ }
+ };
+
+ computeDuration();
+
+ return () => {
+ cancelled = true;
+ };
+ }, [loop, preloadedSrc, logLevel]);
+
+ if (loop && durationInSeconds === null) {
+ return null;
+ }
+
+ return (
+ <AudioForPreviewWithDuration
+ durationInSeconds={durationInSeconds}
+ logLevel={logLevel}
+ muted={muted}
+ playbackRate={playbackRate}
+ src={src}
+ volume={volume}
+ name={name}
+ trimAfter={undefined}
+ trimBefore={undefined}
+ loop={loop}
+ loopVolumeCurveBehavior={loopVolumeCurveBehavior}
+ />
+ );
+};
diff --git a/packages/media/src/audio/audio-player.ts b/packages/media/src/audio/audio-player.ts
new file mode 100644
index 0000000000..f53426133d
--- /dev/null
+++ b/packages/media/src/audio/audio-player.ts
@@ -0,0 +1,361 @@
+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 c29b2a4673..448ca21843 100644
--- a/packages/media/src/audio/audio.tsx
+++ b/packages/media/src/audio/audio.tsx
@@ -1,28 +1,12 @@
-import React, {useCallback, useContext} from 'react';
-import {
- cancelRender,
- Internals,
- Sequence,
- useRemotionEnvironment,
-} from 'remotion';
-import {SharedAudioContext} from '../../../core/src/audio/shared-audio-tags';
+import React from 'react';
+import {Internals, Sequence, useRemotionEnvironment} from 'remotion';
+import {AudioForPreview} from './audio-for-preview';
import {AudioForRendering} from './audio-for-rendering';
import type {AudioProps} from './props';
-const {
- validateMediaTrimProps,
- resolveTrimProps,
- validateMediaProps,
- AudioForPreview,
-} = Internals;
-
-// dummy function for now because onError is not supported
-// eslint-disable-next-line @typescript-eslint/no-unused-vars
-const onRemotionError = (_e: Error) => {};
+const {validateMediaTrimProps, resolveTrimProps, validateMediaProps} = 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 {
@@ -37,8 +21,6 @@ export const Audio: React.FC<AudioProps> = (props) => {
} = 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(
@@ -61,31 +43,6 @@ export const Audio: React.FC<AudioProps> = (props) => {
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);
- }
- },
- [loop],
- );
-
if (
typeof trimBeforeValue !== 'undefined' ||
typeof trimAfterValue !== 'undefined'
@@ -123,20 +80,9 @@ export const Audio: React.FC<AudioProps> = (props) => {
return (
<AudioForPreview
- _remotionInternalNativeLoopPassed={
- props._remotionInternalNativeLoopPassed ?? false
- }
- _remotionInternalStack={stack ?? null}
- shouldPreMountAudioTags={
- audioContext !== null && audioContext.numberOfAudioTags > 0
- }
+ loop={loop}
+ name={name}
{...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/index.ts b/packages/media/src/index.ts
index 91df143273..e69330b8dd 100644
--- a/packages/media/src/index.ts
+++ b/packages/media/src/index.ts
@@ -13,3 +13,4 @@ export const experimental_Video = Video;
export {AudioProps, FallbackHtml5AudioProps} from './audio/props';
export {VideoProps} from './video/props';
export {Audio, Video};
+export {AudioForPreview} from './audio/audio-for-preview';