🎥 Make videos programmatically with React
handle more edge cases
Jonny Burgerd98a0ada8052
diff --git a/packages/core/src/RemotionRoot.tsx b/packages/core/src/RemotionRoot.tsxindex 59f22a724e..9a5d830af1 100644--- a/packages/core/src/RemotionRoot.tsx+++ b/packages/core/src/RemotionRoot.tsx@@ -162,7 +162,7 @@ export const RemotionRoot: React.FC = ({children}) => {<TimelineContext.Provider value={timelineContextValue}><SetTimelineContext.Provider value={setTimelineContextValue}><CompositionManager.Provider value={contextValue}>- <SharedAudioContextProvider numberOfAudioTags={5}>+ <SharedAudioContextProvider numberOfAudioTags={0}>{children}</SharedAudioContextProvider></CompositionManager.Provider>diff --git a/packages/core/src/audio/Audio.tsx b/packages/core/src/audio/Audio.tsxindex f332d104ed..21201dce9f 100644--- a/packages/core/src/audio/Audio.tsx+++ b/packages/core/src/audio/Audio.tsx@@ -1,4 +1,4 @@-import React, {forwardRef, useCallback} from 'react';+import React, {forwardRef, useCallback, useContext} from 'react';import {getRemotionEnvironment} from '../get-environment';import {Sequence} from '../sequencing';import {validateMediaProps} from '../validate-media-props';@@ -6,11 +6,13 @@ import {validateStartFromProps} from '../validate-start-from-props';import {AudioForDevelopment} from './AudioForDevelopment';import {AudioForRendering} from './AudioForRendering';import {RemotionAudioProps, RemotionMainAudioProps} from './props';+import {SharedAudioContext} from './shared-audio-tags';const AudioRefForwardingFunction: React.ForwardRefRenderFunction<HTMLAudioElement,RemotionAudioProps & RemotionMainAudioProps> = (props, ref) => {+ const audioContext = useContext(SharedAudioContext);const {startFrom, endAt, ...otherProps} = props;const onError = useCallback(() => {@@ -40,7 +42,16 @@ const AudioRefForwardingFunction: React.ForwardRefRenderFunction<return <AudioForRendering {...props} ref={ref} onError={onError} />;}- return <AudioForDevelopment {...props} ref={ref} onError={onError} />;+ return (+ <AudioForDevelopment+ shouldPreMountAudioTags={+ audioContext !== null && audioContext.numberOfAudioTags > 0+ }+ {...props}+ ref={ref}+ onError={onError}+ />+ );};export const Audio = forwardRef(AudioRefForwardingFunction);diff --git a/packages/core/src/audio/AudioForDevelopment.tsx b/packages/core/src/audio/AudioForDevelopment.tsxindex ee9a07c572..87e4e24855 100644--- a/packages/core/src/audio/AudioForDevelopment.tsx+++ b/packages/core/src/audio/AudioForDevelopment.tsx@@ -1,4 +1,4 @@-import React, {forwardRef, useImperativeHandle, useMemo} from 'react';+import React, {forwardRef, useImperativeHandle, useMemo, useState} from 'react';import {useMediaInTimeline} from '../use-media-in-timeline';import {useMediaPlayback} from '../use-media-playback';import {useMediaTagVolume} from '../use-media-tag-volume';@@ -13,14 +13,31 @@ import {useFrameForVolumeProp} from './use-audio-frame';const AudioForDevelopmentForwardRefFunction: React.ForwardRefRenderFunction<HTMLAudioElement,- RemotionAudioProps+ RemotionAudioProps & {+ shouldPreMountAudioTags: boolean;+ }> = (props, ref) => {+ const [initialShouldPreMountAudioElements] = useState(+ props.shouldPreMountAudioTags+ );+ if (props.shouldPreMountAudioTags !== initialShouldPreMountAudioElements) {+ throw new Error(+ 'Cannot change the behavior for pre-mounting audio tags dynamically.'+ );+ }+const [mediaVolume] = useMediaVolumeState();const [mediaMuted] = useMediaMutedState();const volumePropFrame = useFrameForVolumeProp();- const {volume, muted, playbackRate, ...nativeProps} = props;+ const {+ volume,+ muted,+ playbackRate,+ shouldPreMountAudioTags,+ ...nativeProps+ } = props;const propsToPass = useMemo((): RemotionAudioProps => {return {@@ -29,38 +46,42 @@ const AudioForDevelopmentForwardRefFunction: React.ForwardRefRenderFunction<};}, [mediaMuted, muted, nativeProps]);- const elem = useSharedAudio(propsToPass);+ const audioRef = useSharedAudio(propsToPass).el;- const actualVolume = useMediaTagVolume(elem.el);+ const actualVolume = useMediaTagVolume(audioRef);useSyncVolumeWithMediaTag({volumePropFrame,actualVolume,volume,mediaVolume,- mediaRef: elem.el,+ mediaRef: audioRef,});useMediaInTimeline({volume,mediaVolume,- mediaRef: elem.el,+ mediaRef: audioRef,src: nativeProps.src,mediaType: 'audio',});useMediaPlayback({- mediaRef: elem.el,+ mediaRef: audioRef,src: nativeProps.src,mediaType: 'audio',playbackRate: playbackRate ?? 1,});useImperativeHandle(ref, () => {- return elem.el.current as HTMLAudioElement;+ return audioRef.current as HTMLAudioElement;});- return null;+ if (initialShouldPreMountAudioElements) {+ return null;+ }++ return <audio ref={audioRef} {...propsToPass} />;};export const AudioForDevelopment = forwardRef(diff --git a/packages/core/src/audio/shared-audio-tags.tsx b/packages/core/src/audio/shared-audio-tags.tsxindex bdf9d18539..102f7ca988 100644--- a/packages/core/src/audio/shared-audio-tags.tsx+++ b/packages/core/src/audio/shared-audio-tags.tsx@@ -24,27 +24,22 @@ type SharedContext = {unregisterAudio: (id: number) => void;updateAudio: (id: number, aud: RemotionAudioProps) => void;playAllAudios: () => void;+ numberOfAudioTags: number;};-export const SharedAudioContext = createContext<SharedContext>({- registerAudio: () => {- throw new Error('sharedaudiocontext not mounted');- },- unregisterAudio: () => {- throw new Error('sharedaudiocontext not mounted');- },- updateAudio: () => {- throw new Error('sharedaudiocontext not mounted');- },- playAllAudios: () => {- throw new Error('sharedaudiocontext not mounted');- },-});+export const SharedAudioContext = createContext<SharedContext | null>(null);export const SharedAudioContextProvider: React.FC<{numberOfAudioTags: number;}> = ({children, numberOfAudioTags}) => {const [audios, setAudios] = useState<AudioElem[]>([]);+ const [initialNumberOfAudioTags] = useState(numberOfAudioTags);++ if (numberOfAudioTags !== initialNumberOfAudioTags) {+ throw new Error(+ 'The number of shared audio tags has changed dynamically. Once you have set this property, you cannot change it afterwards.'+ );+ }const refs = useMemo(() => {return new Array(numberOfAudioTags).fill(true).map(() => {@@ -63,7 +58,7 @@ export const SharedAudioContextProvider: React.FC<{throw new Error(`Tried to simultaneously mount ${numberOfAudioTags + 1- } <Audio /> tags at the same time. The maximum amount of <Audio /> tags is currently limited to ${numberOfAudioTags} at the same time. Remotion pre-mounts silent audio tags to help avoid browser autoplay restrictions. See https://remotion.dev/docs/player#numberofsharedaudiotags for more information on how to increase this limit.`+ } <Audio /> tags at the same time. With the current settings, the maximum amount of <Audio /> tags is limited to ${numberOfAudioTags} at the same time. Remotion pre-mounts silent audio tags to help avoid browser autoplay restrictions. See https://remotion.dev/docs/player#numberofsharedaudiotags for more information on how to increase this limit.`);}@@ -82,7 +77,7 @@ export const SharedAudioContextProvider: React.FC<{}, 4);return newElem;},- [refs, takenAudios]+ [numberOfAudioTags, refs]);const unregisterAudio = useCallback(@@ -90,7 +85,7 @@ export const SharedAudioContextProvider: React.FC<{const cloned = [...takenAudios.current];const index = refs.findIndex((r) => r.id === id);if (index === -1) {- throw new TypeError('unregister audio');+ throw new TypeError('Error occured in ');}cloned[index] = false;@@ -132,8 +127,15 @@ export const SharedAudioContextProvider: React.FC<{unregisterAudio,updateAudio,playAllAudios,+ numberOfAudioTags,};- }, [playAllAudios, registerAudio, unregisterAudio, updateAudio]);+ }, [+ numberOfAudioTags,+ playAllAudios,+ registerAudio,+ unregisterAudio,+ updateAudio,+ ]);return (<SharedAudioContext.Provider value={value}>@@ -163,16 +165,32 @@ export const SharedAudioContextProvider: React.FC<{export const useSharedAudio = (aud: RemotionAudioProps) => {const ctx = useContext(SharedAudioContext);- const [elem] = useState(() => ctx.registerAudio(aud));+ const [elem] = useState(+ (): AudioElem => {+ if (ctx && ctx.numberOfAudioTags > 0) {+ return ctx.registerAudio(aud);+ }++ return {+ el: React.createRef<HTMLAudioElement>(),+ id: Math.random(),+ props: aud,+ };+ }+ );useEffect(() => {return () => {- ctx.unregisterAudio(elem.id);+ if (ctx && ctx.numberOfAudioTags > 0) {+ ctx.unregisterAudio(elem.id);+ }};}, [ctx, elem.id]);useEffect(() => {- ctx.updateAudio(elem.id, aud);+ if (ctx && ctx.numberOfAudioTags > 0) {+ ctx.updateAudio(elem.id, aud);+ }}, [aud, ctx, elem.id]);return elem;diff --git a/packages/docs/docs/player.md b/packages/docs/docs/player.mdindex ddf7fb33e3..19d080364c 100644--- a/packages/docs/docs/player.md+++ b/packages/docs/docs/player.md@@ -133,7 +133,13 @@ A regular `style` prop for a HTMLDivElement. You can pass a different height and_optional - available since v.2.3.1_-If you use an [`<Audio />`](/docs/audio) tag, it might not play in some browsers (specifically iOS Safari) due to browser autoplay policies. This is why the Remotion Player pre-mounts a set of audio tags with silent audio that get played upon user interaction. These audio tags can then be used to play real audio later and will not be subject to the autoplay policy of the browser. This option controls how many audio tags are being rendered, the default is `5`. If you mount more audio tags than shared audio tags are available, then an error will be thrown.+If you use an [`<Audio />`](/docs/audio) tag, it might not play in some browsers (specifically iOS Safari) due to browser autoplay policies. This is why the Remotion Player pre-mounts a set of audio tags with silent audio that get played upon user interaction. These audio tags can then be used to play real audio later and will not be subject to the autoplay policy of the browser.++This option controls how many audio tags are being rendered, the default is `5`. If you mount more audio tags than shared audio tags are available, then an error will be thrown.++If you'd like to opt out of this behavior, you can pass `0` to mount native audio tags simultaneously as you mount Remotion's [`<Audio />`](/docs/audio) tags.++Once you have set this prop, you cannot change it anymore or an error will be thrown.## `PlayerRef`diff --git a/packages/player/src/Player.tsx b/packages/player/src/Player.tsxindex cff858470d..38ff266be1 100644--- a/packages/player/src/Player.tsx+++ b/packages/player/src/Player.tsx@@ -182,10 +182,12 @@ export const PlayerFn = <T,>(if (typeof numberOfSharedAudioTags !== 'number' ||numberOfSharedAudioTags % 1 !== 0 ||+ !Number.isFinite(numberOfSharedAudioTags) ||+ Number.isNaN(numberOfSharedAudioTags) ||numberOfSharedAudioTags < 0) {throw new TypeError(- `'numberOfSharedAudioTags' must be an positive integer but got '${typeof numberOfSharedAudioTags}' instead`+ `'numberOfSharedAudioTags' must be an integer but got '${numberOfSharedAudioTags}' instead`);}diff --git a/packages/player/src/use-player.ts b/packages/player/src/use-player.tsindex ab89ffb365..c3deb7383a 100644--- a/packages/player/src/use-player.ts+++ b/packages/player/src/use-player.ts@@ -50,7 +50,10 @@ export const usePlayer = (): {seek(0);}- audioContext.playAllAudios();+ if (audioContext && audioContext.numberOfAudioTags > 0) {+ audioContext.playAllAudios();+ }+setPlaying(true);emitter.dispatchPlay();}, [playing, isLastFrame, audioContext, setPlaying, emitter, seek]);