Skip to content

🎥 Make videos programmatically with React

`@remotion/player`: Add `_experimentalKeepAudioContextAlive` prop (#10313)

Lucas Igel0d232b65134f
diff --git a/packages/browser-studio/src/BrowserStudio.tsx b/packages/browser-studio/src/BrowserStudio.tsx
index 1896cc037f..921f5b08e7 100644
--- a/packages/browser-studio/src/BrowserStudio.tsx
+++ b/packages/browser-studio/src/BrowserStudio.tsx
@@ -251,6 +251,7 @@ export const BrowserStudio: React.FC<BrowserStudioProps> = ({
const html = studioHtml({
audioLatencyHint: 'playback',
+ experimentalKeepAudioContextAlive: false,
bundleScriptUrl: bundleUrlRef.current,
completedClientRenders: [],
editorName: null,
diff --git a/packages/bundler/src/bundle.ts b/packages/bundler/src/bundle.ts
index 4eb67bfd29..60f9d7576c 100644
--- a/packages/bundler/src/bundle.ts
+++ b/packages/bundler/src/bundle.ts
@@ -448,6 +448,7 @@ export const internalBundle = async (
logLevel: 'info',
mode: 'bundle',
audioLatencyHint: actualArgs.audioLatencyHint ?? 'playback',
+ experimentalKeepAudioContextAlive: false,
sampleRate: actualArgs.renderDefaults?.sampleRate ?? 48000,
studioRuntimeConfig: {
askAIEnabled: actualArgs.askAIEnabled,
diff --git a/packages/cli/src/config/index.ts b/packages/cli/src/config/index.ts
index bd9f878ff5..03726cec6d 100644
--- a/packages/cli/src/config/index.ts
+++ b/packages/cli/src/config/index.ts
@@ -129,6 +129,7 @@ const {
interactivityOption,
keyboardShortcutsOption,
forceNewStudioOption,
+ experimentalKeepAudioContextAliveOption,
numberOfSharedAudioTagsOption,
ipv4Option,
pixelFormatOption,
@@ -238,6 +239,12 @@ declare global {
* @default 0
*/
readonly setNumberOfSharedAudioTags: (numberOfAudioTags: number) => void;
+ /**
+ * Keep the shared AudioContext running while the Remotion Studio is paused.
+ * @param enabled Whether to keep the AudioContext alive.
+ * @default false
+ */
+ readonly setExperimentalKeepAudioContextAlive: (enabled: boolean) => void;
/**
* Enable Webpack polling instead of file system listeners for hot reloading in the Studio.
* This is useful if you are using a remote directory or a virtual machine.
@@ -756,6 +763,8 @@ export const Config: FlatConfig = {
setRspack: rspackOption.setConfig,
setExperimentalRspackEnabled: rspackOption.setConfig,
setNumberOfSharedAudioTags: numberOfSharedAudioTagsOption.setConfig,
+ setExperimentalKeepAudioContextAlive:
+ experimentalKeepAudioContextAliveOption.setConfig,
setWebpackPollingInMilliseconds: webpackPollOption.setConfig,
setShouldOpenBrowser: noOpenOption.setConfig,
setBufferStateDelayInMilliseconds,
diff --git a/packages/cli/src/parsed-cli.ts b/packages/cli/src/parsed-cli.ts
index 1c74ba7eb8..11eac44fe7 100644
--- a/packages/cli/src/parsed-cli.ts
+++ b/packages/cli/src/parsed-cli.ts
@@ -33,6 +33,7 @@ const {
defaultEditorOption,
publicLicenseKeyOption,
forceNewStudioOption,
+ experimentalKeepAudioContextAliveOption,
numberOfSharedAudioTagsOption,
ipv4Option,
pixelFormatOption,
@@ -110,6 +111,9 @@ export type CommandLineOptions = {
[numberOfSharedAudioTagsOption.cliFlag]: TypeOfOption<
typeof numberOfSharedAudioTagsOption
>;
+ [experimentalKeepAudioContextAliveOption.cliFlag]: TypeOfOption<
+ typeof experimentalKeepAudioContextAliveOption
+ > | null;
[offthreadVideoCacheSizeInBytesOption.cliFlag]: TypeOfOption<
typeof offthreadVideoCacheSizeInBytesOption
>;
@@ -226,6 +230,7 @@ export const BooleanFlags = [
reproOption.cliFlag,
isProductionOption.cliFlag,
forceNewStudioOption.cliFlag,
+ experimentalKeepAudioContextAliveOption.cliFlag,
bundleCacheOption.cliFlag,
rspackOption.cliFlag,
skipSkillsOption.cliFlag,
@@ -249,6 +254,7 @@ export const parsedCli = minimist<CommandLineOptions>(process.argv.slice(2), {
[reproOption.cliFlag]: null,
[isProductionOption.cliFlag]: null,
[forceNewStudioOption.cliFlag]: null,
+ [experimentalKeepAudioContextAliveOption.cliFlag]: null,
[mutedOption.cliFlag]: null,
[rspackOption.cliFlag]: null,
},
diff --git a/packages/cli/src/studio.ts b/packages/cli/src/studio.ts
index 63c2d9a794..95a027147e 100644
--- a/packages/cli/src/studio.ts
+++ b/packages/cli/src/studio.ts
@@ -39,6 +39,7 @@ const {
interactivityOption,
keyboardShortcutsOption,
forceNewStudioOption,
+ experimentalKeepAudioContextAliveOption,
numberOfSharedAudioTagsOption,
audioLatencyHintOption,
ipv4Option,
@@ -183,6 +184,10 @@ export const studioCommand = async (
numberOfSharedAudioTagsOption.getValue({commandLine: parsedCli}).value;
const getAudioLatencyHint = () =>
audioLatencyHintOption.getValue({commandLine: parsedCli}).value;
+ const getExperimentalKeepAudioContextAlive = () =>
+ experimentalKeepAudioContextAliveOption.getValue({
+ commandLine: parsedCli,
+ }).value;
const getPreviewSampleRate = () =>
previewSampleRateOption.getValue({commandLine: parsedCli}).value;
const getDefaultCodingAgent = () =>
@@ -312,6 +317,7 @@ export const studioCommand = async (
binariesDirectory,
forceIPv4: ipv4Option.getValue({commandLine: parsedCli}).value,
getAudioLatencyHint,
+ getExperimentalKeepAudioContextAlive,
getPreviewSampleRate,
getDefaultCodingAgent,
getDefaultEditor,
diff --git a/packages/cli/src/test/config-file-change.test.ts b/packages/cli/src/test/config-file-change.test.ts
index 7f1248ed60..b731f6b22d 100644
--- a/packages/cli/src/test/config-file-change.test.ts
+++ b/packages/cli/src/test/config-file-change.test.ts
@@ -49,6 +49,16 @@ test('classifies changes that require a page reload', () => {
prepare('import_config.Config.setAudioLatencyHint("interactive");'),
),
).toBe('reload');
+ expect(
+ classify(
+ prepare(
+ 'import_config.Config.setExperimentalKeepAudioContextAlive(false);',
+ ),
+ prepare(
+ 'import_config.Config.setExperimentalKeepAudioContextAlive(true);',
+ ),
+ ),
+ ).toBe('reload');
});
test('classifies changes that require a Studio restart', () => {
diff --git a/packages/cli/src/test/config-reset.test.ts b/packages/cli/src/test/config-reset.test.ts
index c895eb9925..e9e4f9b169 100644
--- a/packages/cli/src/test/config-reset.test.ts
+++ b/packages/cli/src/test/config-reset.test.ts
@@ -40,6 +40,7 @@ test('reset config options restores defaults before reloading config', async ()
Config.setDefaultCodingAgent('codex');
Config.setDefaultEditor('cursor');
Config.setBufferStateDelayInMilliseconds(200);
+ Config.setExperimentalKeepAudioContextAlive(true);
Config.overrideBundlerConfig((config, {bundler}) => ({
...config,
name: `shared-${bundler}`,
@@ -72,6 +73,11 @@ test('reset config options restores defaults before reloading config', async ()
.value,
).toBe('cursor');
expect(ConfigInternals.getBufferStateDelayInMilliseconds()).toBe(200);
+ expect(
+ BrowserSafeApis.options.experimentalKeepAudioContextAliveOption.getValue({
+ commandLine: {},
+ }).value,
+ ).toBe(true);
const sharedWebpackConfig = await ConfigInternals.getBundlerOverrideFn()(
{mode: 'development'},
{bundler: 'webpack'},
@@ -117,6 +123,11 @@ test('reset config options restores defaults before reloading config', async ()
.value,
).toBeNull();
expect(ConfigInternals.getBufferStateDelayInMilliseconds()).toBeNull();
+ expect(
+ BrowserSafeApis.options.experimentalKeepAudioContextAliveOption.getValue({
+ commandLine: {},
+ }).value,
+ ).toBe(false);
expect(
await ConfigInternals.getBundlerOverrideFn()(
{mode: 'development'},
@@ -153,7 +164,13 @@ test('CLI app flags take precedence over the configured defaults', () => {
executable: '/opt/acme/editor',
arguments: ['--goto', '%TARGET_PATH%:%LINE_NUMBER%:%COLUMN_NUMBER%'],
});
+ Config.setExperimentalKeepAudioContextAlive(false);
+ expect(
+ BrowserSafeApis.options.experimentalKeepAudioContextAliveOption.getValue({
+ commandLine: {'experimental-keep-audio-context-alive': true},
+ }),
+ ).toEqual({source: 'cli', value: true});
expect(
BrowserSafeApis.options.defaultCodingAgentOption.getValue({
commandLine: {'coding-agent': 'cursor'},
diff --git a/packages/core/src/RemotionRoot.tsx b/packages/core/src/RemotionRoot.tsx
index 1ed0e30bcc..dcbc956dde 100644
--- a/packages/core/src/RemotionRoot.tsx
+++ b/packages/core/src/RemotionRoot.tsx
@@ -25,6 +25,7 @@ export const RemotionRootContexts: React.FC<{
readonly videoEnabled: boolean;
readonly audioEnabled: boolean;
readonly frameState: Record<string, number> | null;
+ readonly _experimentalKeepAudioContextAlive: boolean;
}> = ({
children,
numberOfAudioTags,
@@ -34,6 +35,7 @@ export const RemotionRootContexts: React.FC<{
videoEnabled,
audioEnabled,
frameState,
+ _experimentalKeepAudioContextAlive,
}) => {
const nonceContext = useMemo((): TNonceContext => {
let counter = 0;
@@ -63,6 +65,9 @@ export const RemotionRootContexts: React.FC<{
audioLatencyHint={audioLatencyHint}
audioEnabled={audioEnabled}
previewSampleRate={previewSampleRate}
+ _experimentalKeepAudioContextAlive={
+ _experimentalKeepAudioContextAlive
+ }
>
<SharedAudioTagsContextProvider
numberOfAudioTags={numberOfAudioTags}
diff --git a/packages/core/src/audio/shared-audio-tags.tsx b/packages/core/src/audio/shared-audio-tags.tsx
index 213097b8e3..f51b603a4c 100644
--- a/packages/core/src/audio/shared-audio-tags.tsx
+++ b/packages/core/src/audio/shared-audio-tags.tsx
@@ -91,6 +91,7 @@ type SharedAudioContextValue = {
suspend: () => Promise<void>;
getIsResumingAudioContext: () => Promise<AudioContextResumeResult> | null;
unscheduleAudioNode: (node: AudioBufferSourceNode) => void;
+ _experimentalKeepAudioContextAlive: boolean;
};
type SharedAudioTagsContextValue = {
@@ -205,7 +206,14 @@ export const SharedAudioContextProvider: React.FC<{
readonly audioLatencyHint: AudioContextLatencyCategory;
readonly audioEnabled: boolean;
readonly previewSampleRate: number | null;
-}> = ({children, audioLatencyHint, audioEnabled, previewSampleRate}) => {
+ readonly _experimentalKeepAudioContextAlive: boolean;
+}> = ({
+ children,
+ audioLatencyHint,
+ audioEnabled,
+ previewSampleRate,
+ _experimentalKeepAudioContextAlive,
+}) => {
const logLevel = useLogLevel();
const sampleRate = previewSampleRate ?? 48000;
@@ -224,6 +232,19 @@ export const SharedAudioContextProvider: React.FC<{
sampleRate,
});
const audioContextIsPlayingEventually = useRef(false);
+ const initialExperimentalKeepAudioContextAlive = useRef(
+ _experimentalKeepAudioContextAlive,
+ );
+
+ if (
+ initialExperimentalKeepAudioContextAlive.current !==
+ _experimentalKeepAudioContextAlive
+ ) {
+ throw new Error(
+ '`_experimentalKeepAudioContextAlive` cannot be changed dynamically.',
+ );
+ }
+
const isResuming = useRef<AudioContextResumeAttempt | null>(null);
const nextResumeAttemptId = useRef(0);
@@ -283,7 +304,15 @@ export const SharedAudioContextProvider: React.FC<{
};
}
- const saveForLater = shouldSaveForLater(currentState);
+ // With _experimentalKeepAudioContextAlive, the native context stays
+ // `running` while silenced, so the state alone does not reveal that playback
+ // is paused. Queue the node like the suspend path does, otherwise it
+ // would start right away at a stale position and become audible when
+ // the gain ramps back up.
+ const saveForLater =
+ shouldSaveForLater(currentState) ||
+ (_experimentalKeepAudioContextAlive &&
+ !audioContextIsPlayingEventually.current);
if (duration > 0) {
if (saveForLater) {
@@ -361,7 +390,7 @@ export const SharedAudioContextProvider: React.FC<{
reason: 'missed ' + Math.abs(offset).toFixed(2) + 's',
};
};
- }, [ctxAndGain, logLevel]);
+ }, [ctxAndGain, _experimentalKeepAudioContextAlive, logLevel]);
const resume = useCallback(() => {
if (!ctxAndGain) {
@@ -391,6 +420,16 @@ export const SharedAudioContextProvider: React.FC<{
});
nodesToResume.current.clear();
+ if (
+ _experimentalKeepAudioContextAlive &&
+ ctxAndGain.audioContext.state === 'running'
+ ) {
+ // The context was never suspended, so there is nothing to wait for:
+ // the resume-wait machinery, its timeout and the mute-on-failure
+ // path are not entered.
+ return Promise.resolve();
+ }
+
const resumePromise = ctxAndGain.resume();
const abortController = new AbortController();
const resumeAttemptId = nextResumeAttemptId.current++;
@@ -425,7 +464,7 @@ export const SharedAudioContextProvider: React.FC<{
// Already logged above; swallow to avoid unhandled rejection
// since callers (e.g. use-playback.ts) do not await this.
});
- }, [ctxAndGain, logLevel]);
+ }, [ctxAndGain, _experimentalKeepAudioContextAlive, logLevel]);
const getIsResumingAudioContext = useCallback(() => {
return isResuming.current?.promise ?? null;
@@ -443,8 +482,70 @@ export const SharedAudioContextProvider: React.FC<{
}
audioContextIsPlayingEventually.current = false;
+
+ if (_experimentalKeepAudioContextAlive) {
+ // Silence through the gain instead of suspending, so the context
+ // clock keeps running and the next resume() is instant. Audio that
+ // is already scheduled plays out silently; resume() ramps the gain
+ // back up.
+ ctxAndGain.gainNode.gain.cancelScheduledValues(
+ ctxAndGain.audioContext.currentTime,
+ );
+ ctxAndGain.gainNode.gain.setValueAtTime(
+ 0,
+ ctxAndGain.audioContext.currentTime,
+ );
+ return Promise.resolve();
+ }
+
return ctxAndGain.suspend();
- }, [ctxAndGain]);
+ }, [ctxAndGain, _experimentalKeepAudioContextAlive]);
+
+ // With _experimentalKeepAudioContextAlive, start the context as early as
+ // possible so the first play never waits on the suspended→running transition. Where
+ // no autoplay restriction applies (e.g. Electron with
+ // `no-user-gesture-required`), the mount attempt succeeds immediately;
+ // in a browser the first user gesture starts it. suspend() never reaches
+ // the native context in this mode, so once running it stays running.
+ // The cleanup suspends the native context, since Player contexts are
+ // not close()d and must not be left running after unmount.
+ useEffect(() => {
+ if (!_experimentalKeepAudioContextAlive) {
+ return;
+ }
+
+ if (!ctxAndGain) {
+ return;
+ }
+
+ if (typeof window === 'undefined') {
+ return;
+ }
+
+ const wake = () => {
+ if (ctxAndGain.audioContext.state === 'running') {
+ return;
+ }
+
+ ctxAndGain.resume().catch(() => {
+ // A rejection here means autoplay is still blocked; a later
+ // gesture will retry.
+ });
+ };
+
+ wake();
+ window.addEventListener('pointerdown', wake, {
+ capture: true,
+ passive: true,
+ });
+ window.addEventListener('keydown', wake, {capture: true, passive: true});
+
+ return () => {
+ window.removeEventListener('pointerdown', wake, {capture: true});
+ window.removeEventListener('keydown', wake, {capture: true});
+ ctxAndGain.suspend().catch(() => {});
+ };
+ }, [ctxAndGain, _experimentalKeepAudioContextAlive]);
const audioContextValue: SharedAudioContextValue = useMemo(() => {
return {
@@ -458,6 +559,7 @@ export const SharedAudioContextProvider: React.FC<{
suspend,
getIsResumingAudioContext,
unscheduleAudioNode,
+ _experimentalKeepAudioContextAlive,
};
}, [
ctxAndGain,
@@ -468,6 +570,7 @@ export const SharedAudioContextProvider: React.FC<{
suspend,
getIsResumingAudioContext,
unscheduleAudioNode,
+ _experimentalKeepAudioContextAlive,
]);
return (
diff --git a/packages/core/src/test/composition-rules.test.tsx b/packages/core/src/test/composition-rules.test.tsx
index 96193b2e33..c85453d2f6 100644
--- a/packages/core/src/test/composition-rules.test.tsx
+++ b/packages/core/src/test/composition-rules.test.tsx
@@ -59,6 +59,7 @@ describe('Render composition-rules should throw with invalid props', () => {
initialCanvasContent={null}
>
<RemotionRootContexts
+ _experimentalKeepAudioContextAlive={false}
frameState={null}
videoEnabled
audioEnabled
diff --git a/packages/core/src/test/keep-audio-context-alive.test.tsx b/packages/core/src/test/keep-audio-context-alive.test.tsx
new file mode 100644
index 0000000000..9f664f59a8
--- /dev/null
+++ b/packages/core/src/test/keep-audio-context-alive.test.tsx
@@ -0,0 +1,218 @@
+import {afterEach, expect, test} from 'bun:test';
+import {act, cleanup, render} from '@testing-library/react';
+import type React from 'react';
+import {useContext} from 'react';
+import {
+ SharedAudioContext,
+ SharedAudioContextProvider,
+} from '../audio/shared-audio-tags.js';
+import {RemotionEnvironmentContext} from '../remotion-environment-context.js';
+import {WrapSequenceContext} from './wrap-sequence-context.js';
+
+afterEach(() => {
+ cleanup();
+});
+
+const previewEnvironment = {
+ isClientSideRendering: false,
+ isPlayer: true,
+ isReadOnlyStudio: false,
+ isRendering: false,
+ isStudio: false,
+};
+
+let nativeSuspendCalls = 0;
+let gainValues: number[] = [];
+
+class TrackedAudioContext {
+ public state = 'suspended' as AudioContextState;
+ public baseLatency = 0;
+ public outputLatency = 0;
+ public currentTime = 0;
+ public destination = {};
+
+ addEventListener() {
+ return undefined;
+ }
+
+ removeEventListener() {
+ return undefined;
+ }
+
+ createGain() {
+ return {
+ connect: () => undefined,
+ gain: {
+ cancelScheduledValues: () => undefined,
+ linearRampToValueAtTime: () => undefined,
+ setValueAtTime: (value: number) => {
+ gainValues.push(value);
+ },
+ },
+ };
+ }
+
+ suspend() {
+ nativeSuspendCalls++;
+ this.state = 'suspended';
+ return Promise.resolve();
+ }
+
+ resume() {
+ this.state = 'running';
+ return Promise.resolve();
+ }
+
+ getOutputTimestamp() {
+ return {contextTime: this.currentTime, performanceTime: 0};
+ }
+
+ createMediaElementSource() {
+ return {
+ connect: () => undefined,
+ disconnect: () => undefined,
+ };
+ }
+}
+
+const makeNode = (started: number[]) => {
+ return {
+ playbackRate: {value: 1},
+ start: (scheduledTime: number) => {
+ started.push(scheduledTime);
+ },
+ } as unknown as AudioBufferSourceNode;
+};
+
+const scheduleAt = (
+ value: NonNullable<React.ContextType<typeof SharedAudioContext>>,
+ node: AudioBufferSourceNode,
+ scheduledTime: number,
+) => {
+ return value.scheduleAudioNode({
+ node,
+ mediaTimestamp: 0,
+ sourceOffset: 0,
+ scheduledTime,
+ duration: 1,
+ offset: 0,
+ originalUnloopedMediaTimestamp: 0,
+ });
+};
+
+const renderProvider = (_experimentalKeepAudioContextAlive: boolean) => {
+ const ref: {
+ current: NonNullable<React.ContextType<typeof SharedAudioContext>> | null;
+ } = {current: null};
+
+ const Probe: React.FC = () => {
+ ref.current = useContext(SharedAudioContext);
+ return null;
+ };
+
+ render(
+ <RemotionEnvironmentContext.Provider value={previewEnvironment}>
+ <WrapSequenceContext>
+ <SharedAudioContextProvider
+ audioEnabled
+ audioLatencyHint="interactive"
+ previewSampleRate={null}
+ _experimentalKeepAudioContextAlive={
+ _experimentalKeepAudioContextAlive
+ }
+ >
+ <Probe />
+ </SharedAudioContextProvider>
+ </WrapSequenceContext>
+ </RemotionEnvironmentContext.Provider>,
+ );
+
+ if (!ref.current) {
+ throw new Error('Expected the shared audio context to be available');
+ }
+
+ return ref.current;
+};
+
+const withMockedAudioContext = async (fn: () => Promise<void>) => {
+ const originalAudioContext = globalThis.AudioContext;
+ globalThis.AudioContext =
+ TrackedAudioContext as unknown as typeof AudioContext;
+ nativeSuspendCalls = 0;
+ gainValues = [];
+ try {
+ await fn();
+ } finally {
+ globalThis.AudioContext = originalAudioContext;
+ }
+};
+
+test('suspend() suspends the AudioContext by default', async () => {
+ await withMockedAudioContext(async () => {
+ const value = renderProvider(false);
+
+ await act(async () => {
+ value.resume();
+ await Promise.resolve();
+ });
+ nativeSuspendCalls = 0;
+
+ await act(async () => {
+ value.suspend();
+ await Promise.resolve();
+ });
+ expect(nativeSuspendCalls).toBe(1);
+ });
+});
+
+test('_experimentalKeepAudioContextAlive silences the gain instead of suspending', async () => {
+ await withMockedAudioContext(async () => {
+ const value = renderProvider(true);
+
+ await act(async () => {
+ value.resume();
+ await Promise.resolve();
+ });
+ nativeSuspendCalls = 0;
+ gainValues = [];
+
+ await act(async () => {
+ value.suspend();
+ await Promise.resolve();
+ });
+ expect(nativeSuspendCalls).toBe(0);
+ expect(gainValues).toContain(0);
+ });
+});
+
+test('_experimentalKeepAudioContextAlive queues nodes scheduled while silenced', async () => {
+ await withMockedAudioContext(async () => {
+ const value = renderProvider(true);
+
+ await act(async () => {
+ value.resume();
+ await Promise.resolve();
+ });
+
+ const startedWhileRunning: number[] = [];
+ scheduleAt(value, makeNode(startedWhileRunning), 1);
+ expect(startedWhileRunning).toEqual([1]);
+
+ await act(async () => {
+ value.suspend();
+ await Promise.resolve();
+ });
+
+ // The native state is still 'running' here, so the node must be queued
+ // based on the silenced state rather than on the context state.
+ const startedWhileSilenced: number[] = [];
+ scheduleAt(value, makeNode(startedWhileSilenced), 2);
+ expect(startedWhileSilenced).toEqual([]);
+
+ await act(async () => {
+ value.resume();
+ await Promise.resolve();
+ });
+ expect(startedWhileSilenced).toEqual([2]);
+ });
+});
diff --git a/packages/core/src/test/offthread-video.test.tsx b/packages/core/src/test/offthread-video.test.tsx
index 956fbac401..f08bfe0e01 100644
--- a/packages/core/src/test/offthread-video.test.tsx
+++ b/packages/core/src/test/offthread-video.test.tsx
@@ -28,6 +28,7 @@ const WrapPreviewContext: React.FC<{
audioEnabled={false}
audioLatencyHint="playback"
previewSampleRate={null}
+ _experimentalKeepAudioContextAlive={false}
>
{children}
</SharedAudioContextProvider>
diff --git a/packages/docs/docs/cli/studio.mdx b/packages/docs/docs/cli/studio.mdx
index d35c0d4035..70bb9825a6 100644
--- a/packages/docs/docs/cli/studio.mdx
+++ b/packages/docs/docs/cli/studio.mdx
@@ -127,6 +127,18 @@ npx remotion studio --ipv4
npx remotion studio --number-of-shared-audio-tags=5
```
+### `--experimental-keep-audio-context-alive`<AvailableFrom v="4.0.508" />
+
+<ExperimentalBadge>
+ <p>We are currently testing this prop. We might either remove the functionality or rename the prop to a stable name.</p>
+</ExperimentalBadge>
+
+<Options id="experimental-keep-audio-context-alive" />
+
+```sh
+npx remotion studio --experimental-keep-audio-context-alive
+```
+
### `--preview-sample-rate`
<Options id="preview-sample-rate" />
diff --git a/packages/docs/docs/config.mdx b/packages/docs/docs/config.mdx
index a37b881659..5d0ae2bc22 100644
--- a/packages/docs/docs/config.mdx
+++ b/packages/docs/docs/config.mdx
@@ -929,6 +929,26 @@ Config.setAudioLatencyHint('interactive');
The `--audio-latency-hint` command line flag will take precedence over this option.
+## `setExperimentalKeepAudioContextAlive()`<AvailableFrom v="4.0.508" />
+
+<ExperimentalBadge>
+ <p>We are currently testing this prop. We might either remove the functionality or rename the prop to a stable name.</p>
+</ExperimentalBadge>
+
+<Options id="experimental-keep-audio-context-alive" />
+<br />
+<br />
+
+Keeps the shared [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) running while the Remotion Studio is paused. Pausing lowers the gain to zero rather than suspending the context, which can reduce latency when resuming playback.
+
+```ts twoslash title="remotion.config.ts"
+import {Config} from '@remotion/cli/config';
+// ---cut---
+Config.setExperimentalKeepAudioContextAlive(true);
+```
+
+Changing this option while the Studio is running reloads the page. The `--experimental-keep-audio-context-alive` command line flag will take precedence over this option.
+
## `setEnableFolderExpiry()`<AvailableFrom v="4.0.32" />
<Options id="enable-folder-expiry" />
diff --git a/packages/docs/docs/player/api.mdx b/packages/docs/docs/player/api.mdx
index b083966795..52ec70bbde 100644
--- a/packages/docs/docs/player/api.mdx
+++ b/packages/docs/docs/player/api.mdx
@@ -485,6 +485,30 @@ If you pass this prop, the Player **does not** read the starting volume from `lo
/>
```
+### `_experimentalKeepAudioContextAlive?`<AvailableFrom v="4.0.508" />
+
+<ExperimentalBadge>
+<p>We are currently testing this prop. We might either remove the functionality or rename the prop to a stable name.</p>
+</ExperimentalBadge>
+
+Keeps the [`AudioContext`](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext) running while the Player is paused, instead of suspending it. Pausing lowers the gain to zero rather than stopping the context, so the next `play()` does not have to wait for the context to come back up.
+
+This is meant for editor-style applications (video editors, DAW-like tools) that play and pause many times per session, where the delay of resuming the context on every play is noticeable. For a Player that is played a few times, leave this off.
+
+The context is started when the Player mounts if the browser's autoplay policy allows it, otherwise on the first click or key press. It is suspended again when the Player unmounts.
+
+The value cannot be changed after the Player mounts. Doing so throws an error.
+
+**Example:**
+
+```tsx title="MyPlayer.tsx"
+<Player
+ component={MyVideo}
+ // ... other props
+ _experimentalKeepAudioContextAlive
+/>
+```
+
## `PlayerRef`
You may attach a ref to the player and control it in an imperative manner.
diff --git a/packages/player/src/Player.tsx b/packages/player/src/Player.tsx
index a9d900bec5..b5d13761ff 100644
--- a/packages/player/src/Player.tsx
+++ b/packages/player/src/Player.tsx
@@ -100,6 +100,7 @@ export type PlayerProps<
readonly sampleRate?: number;
readonly volumePersistenceKey?: string;
readonly initialVolume?: number;
+ readonly _experimentalKeepAudioContextAlive?: boolean;
} & CompProps<Props> &
PropsIfHasProps<Schema, Props>;
@@ -172,6 +173,7 @@ const PlayerFn = <
sampleRate = 48000,
volumePersistenceKey,
initialVolume,
+ _experimentalKeepAudioContextAlive = false,
...componentProps
}: PlayerProps<Schema, Props>,
ref: RefObject<PlayerRef>,
@@ -449,6 +451,7 @@ const PlayerFn = <
logLevel={logLevel}
audioLatencyHint={audioLatencyHint}
sampleRate={sampleRate}
+ _experimentalKeepAudioContextAlive={_experimentalKeepAudioContextAlive}
volumePersistenceKey={volumePersistenceKey}
initialVolume={initialVolume}
inputProps={actualInputProps}
diff --git a/packages/player/src/SharedPlayerContext.tsx b/packages/player/src/SharedPlayerContext.tsx
index b924e62fdc..1d7035ad91 100644
--- a/packages/player/src/SharedPlayerContext.tsx
+++ b/packages/player/src/SharedPlayerContext.tsx
@@ -37,6 +37,7 @@ export const SharedPlayerContexts: React.FC<{
readonly initialVolume?: number;
readonly inputProps: Record<string, unknown>;
readonly audioEnabled: boolean;
+ readonly _experimentalKeepAudioContextAlive: boolean;
}> = ({
children,
timelineContext,
@@ -55,6 +56,7 @@ export const SharedPlayerContexts: React.FC<{
initialVolume,
inputProps,
audioEnabled,
+ _experimentalKeepAudioContextAlive,
}) => {
const persistVolumeToStorage = initialVolume === undefined;
const compositionManagerContext: CompositionManagerContext = useMemo(() => {
@@ -194,6 +196,9 @@ export const SharedPlayerContexts: React.FC<{
audioLatencyHint={audioLatencyHint}
audioEnabled={shouldCreateAudioContext}
previewSampleRate={sampleRate}
+ _experimentalKeepAudioContextAlive={
+ _experimentalKeepAudioContextAlive
+ }
>
<Internals.SharedAudioTagsContextProvider
numberOfAudioTags={numberOfSharedAudioTags}
diff --git a/packages/player/src/Thumbnail.tsx b/packages/player/src/Thumbnail.tsx
index 1a256a1053..849a48d215 100644
--- a/packages/player/src/Thumbnail.tsx
+++ b/packages/player/src/Thumbnail.tsx
@@ -139,6 +139,7 @@ const ThumbnailFn = <
sampleRate={48000}
inputProps={passedInputProps}
audioEnabled={false}
+ _experimentalKeepAudioContextAlive={false}
>
<ThumbnailEmitterContext.Provider value={emitter}>
<ThumbnailUI
diff --git a/packages/player/src/test/keep-audio-context-alive.test.tsx b/packages/player/src/test/keep-audio-context-alive.test.tsx
new file mode 100644
index 0000000000..a1f44f768a
--- /dev/null
+++ b/packages/player/src/test/keep-audio-context-alive.test.tsx
@@ -0,0 +1,176 @@
+import {afterEach, expect, test} from 'bun:test';
+import {createRef} from 'react';
+import {Html5Audio, Internals} from 'remotion';
+import type {PlayerRef} from '../player-methods.js';
+import {Player} from '../Player.js';
+import {act, cleanup, render} from './test-utils.js';
+
+afterEach(() => {
+ cleanup();
+});
+
+let nativeSuspendCalls = 0;
+let nativeResumeCalls = 0;
+let gainValues: number[] = [];
+
+class TrackedAudioContext {
+ public state = 'suspended' as AudioContextState;
+ public baseLatency = 0;
+ public outputLatency = 0;
+ public currentTime = 0;
+ public destination = {};
+
+ addEventListener() {
+ return undefined;
+ }
+
+ removeEventListener() {
+ return undefined;
+ }
+
+ createGain() {
+ return {
+ connect: () => undefined,
+ gain: {
+ cancelScheduledValues: () => undefined,
+ linearRampToValueAtTime: () => undefined,
+ setValueAtTime: (value: number) => {
+ gainValues.push(value);
+ },
+ },
+ };
+ }
+
+ suspend() {
+ nativeSuspendCalls++;
+ this.state = 'suspended';
+ return Promise.resolve();
+ }
+
+ resume() {
+ nativeResumeCalls++;
+ this.state = 'running';
+ return Promise.resolve();
+ }
+
+ getOutputTimestamp() {
+ return {contextTime: 0, performanceTime: 0};
+ }
+
+ createMediaElementSource() {
+ return {
+ connect: () => undefined,
+ disconnect: () => undefined,
+ };
+ }
+}
+
+const sequenceManager = {
+ registerSequence: () => undefined,
+ unregisterSequence: () => undefined,
+ sequences: [],
+};
+
+const AudioComposition = () => {
+ return (
+ <Internals.SequenceManager.Provider value={sequenceManager}>
+ <Html5Audio src="audio.mp3" />
+ </Internals.SequenceManager.Provider>
+ );
+};
+
+const playAndPause = async ({
+ _experimentalKeepAudioContextAlive,
+}: {
+ _experimentalKeepAudioContextAlive: boolean;
+}) => {
+ const originalAudioContext = globalThis.AudioContext;
+ const originalRequestAnimationFrame = globalThis.requestAnimationFrame;
+ const originalCancelAnimationFrame = globalThis.cancelAnimationFrame;
+
+ let animationFrameId = 0;
+ const animationFrames = new Map<number, FrameRequestCallback>();
+
+ globalThis.AudioContext =
+ TrackedAudioContext as unknown as typeof AudioContext;
+ globalThis.requestAnimationFrame = (callback) => {
+ animationFrameId++;
+ animationFrames.set(animationFrameId, callback);
+ return animationFrameId;
+ };
+
+ globalThis.cancelAnimationFrame = (id) => {
+ animationFrames.delete(id);
+ };
+
+ try {
+ nativeSuspendCalls = 0;
+ nativeResumeCalls = 0;
+ gainValues = [];
+
+ const playerRef = createRef<PlayerRef>();
+ render(
+ <Player
+ ref={playerRef}
+ component={AudioComposition}
+ durationInFrames={300}
+ compositionWidth={1920}
+ compositionHeight={1080}
+ fps={30}
+ _experimentalKeepAudioContextAlive={_experimentalKeepAudioContextAlive}
+ />,
+ );
+
+ // The context is suspended once upon creation.
+ expect(nativeSuspendCalls).toBe(1);
+ nativeSuspendCalls = 0;
+ nativeResumeCalls = 0;
+ gainValues = [];
+
+ await act(async () => {
+ playerRef.current?.play();
+ await Promise.resolve();
+ });
+
+ const resumeCallsDuringPlay = nativeResumeCalls;
+ gainValues = [];
+
+ await act(async () => {
+ playerRef.current?.pause();
+ await Promise.resolve();
+ });
+
+ return {
+ resumeCallsDuringPlay,
+ suspendCallsDuringPause: nativeSuspendCalls,
+ gainValuesDuringPause: gainValues,
+ };
+ } finally {
+ globalThis.AudioContext = originalAudioContext;
+ globalThis.requestAnimationFrame = originalRequestAnimationFrame;
+ globalThis.cancelAnimationFrame = originalCancelAnimationFrame;
+ }
+};
+
+test('Pausing suspends the AudioContext by default', async () => {
+ const {resumeCallsDuringPlay, suspendCallsDuringPause} = await playAndPause({
+ _experimentalKeepAudioContextAlive: false,
+ });
+
+ expect(resumeCallsDuringPlay).toBe(1);
+ expect(suspendCallsDuringPause).toBe(1);
+});
+
+test('_experimentalKeepAudioContextAlive silences through the gain instead of suspending', async () => {
+ const {
+ resumeCallsDuringPlay,
+ suspendCallsDuringPause,
+ gainValuesDuringPause,
+ } = await playAndPause({_experimentalKeepAudioContextAlive: true});
+
+ // The context was already started on mount, so playing does not need to
+ // resume it again.
+ expect(resumeCallsDuringPlay).toBe(0);
+ expect(suspendCallsDuringPause).toBe(0);
+ expect(gainValuesDuringPause).toContain(0);
+});
diff --git a/packages/player/src/test/validate-prop.test.tsx b/packages/player/src/test/validate-prop.test.tsx
index 4a1e8eefd9..754039e893 100644
--- a/packages/player/src/test/validate-prop.test.tsx
+++ b/packages/player/src/test/validate-prop.test.tsx
@@ -414,6 +414,34 @@ test('sampleRate cannot be changed dynamically', () => {
);
});
+test('_experimentalKeepAudioContextAlive cannot be changed dynamically', () => {
+ const initial = (
+ <Player
+ compositionWidth={500}
+ compositionHeight={400}
+ fps={30}
+ durationInFrames={500}
+ component={HelloWorld}
+ />
+ );
+ const changed = (
+ <Player
+ compositionWidth={500}
+ compositionHeight={400}
+ fps={30}
+ durationInFrames={500}
+ component={HelloWorld}
+ _experimentalKeepAudioContextAlive
+ />
+ );
+
+ const {rerender} = render(initial);
+
+ expect(() => rerender(changed)).toThrow(
+ /`_experimentalKeepAudioContextAlive` cannot be changed dynamically/,
+ );
+});
+
test('invalid sampleRate should give errors', () => {
expect(() => {
render(
diff --git a/packages/player/src/use-playback.ts b/packages/player/src/use-playback.ts
index 5924525ec3..37d7c24e5b 100644
--- a/packages/player/src/use-playback.ts
+++ b/packages/player/src/use-playback.ts
@@ -162,6 +162,32 @@ export const usePlayback = ({
return;
}
+ if (
+ sharedAudioContext?._experimentalKeepAudioContextAlive &&
+ sharedAudioContext.audioContext &&
+ !muted
+ ) {
+ // With _experimentalKeepAudioContextAlive, the context clock keeps
+ // running while frames are not advancing (pauses, buffering, muted playback), so
+ // the anchor is stale by the length of the stall. Without this mode,
+ // the 'statechange' listener above re-anchors on the
+ // suspended-to-running transition, but that transition never happens
+ // here. Re-anchor from the current frame instead, and tell the audio
+ // iterators so they drop the nodes they queued against the old
+ // anchor and reschedule.
+ const changed = setGlobalTimeAnchor({
+ audioContext: sharedAudioContext.audioContext,
+ audioSyncAnchor: sharedAudioContext.audioSyncAnchor,
+ absoluteTimeInSeconds: getCurrentFrame() / config.fps,
+ globalPlaybackRate: playbackRate,
+ logLevel,
+ force: true,
+ });
+ if (changed) {
+ sharedAudioContext.audioSyncAnchorEmitter.dispatch('changed');
+ }
+ }
+
let hasBeenStopped = false;
let audioContextFailed = false;
let reqAnimFrameCall:
diff --git a/packages/renderer/src/options/experimental-keep-audio-context-alive.tsx b/packages/renderer/src/options/experimental-keep-audio-context-alive.tsx
new file mode 100644
index 0000000000..c85474affe
--- /dev/null
+++ b/packages/renderer/src/options/experimental-keep-audio-context-alive.tsx
@@ -0,0 +1,37 @@
+import type {AnyRemotionOption} from './option';
+
+let experimentalKeepAudioContextAlive = false;
+
+const cliFlag = 'experimental-keep-audio-context-alive' as const;
+
+export const experimentalKeepAudioContextAliveOption = {
+ name: 'Keep AudioContext alive (experimental)',
+ cliFlag,
+ description: () => (
+ <>
+ Keeps the shared <code>AudioContext</code> running while the Remotion
+ Studio is paused.
+ </>
+ ),
+ ssrName: null,
+ docLink:
+ 'https://www.remotion.dev/docs/config#setexperimentalkeepaudiocontextalive',
+ type: false as boolean,
+ getValue: ({commandLine}) => {
+ if (commandLine[cliFlag] !== undefined && commandLine[cliFlag] !== null) {
+ return {
+ value: commandLine[cliFlag] as boolean,
+ source: 'cli',
+ };
+ }
+
+ return {
+ value: experimentalKeepAudioContextAlive,
+ source: 'config',
+ };
+ },
+ setConfig(value) {
+ experimentalKeepAudioContextAlive = value;
+ },
+ id: cliFlag,
+} satisfies AnyRemotionOption<boolean>;
diff --git a/packages/renderer/src/options/index.tsx b/packages/renderer/src/options/index.tsx
index 92739f4843..ad26feeb60 100644
--- a/packages/renderer/src/options/index.tsx
+++ b/packages/renderer/src/options/index.tsx
@@ -28,6 +28,7 @@ import {encodingMaxRateOption} from './encoding-max-rate';
import {enforceAudioOption} from './enforce-audio';
import {envFileOption} from './env-file';
import {everyNthFrameOption} from './every-nth-frame';
+import {experimentalKeepAudioContextAliveOption} from './experimental-keep-audio-context-alive';
import {folderExpiryOption} from './folder-expiry';
import {forSeamlessAacConcatenationOption} from './for-seamless-aac-concatenation';
import {forceNewStudioOption} from './force-new-studio';
@@ -163,6 +164,7 @@ export const allOptions = {
keyboardShortcutsOption,
framesOption,
forceNewStudioOption,
+ experimentalKeepAudioContextAliveOption,
numberOfSharedAudioTagsOption,
ipv4Option,
stillImageFormatOption,
diff --git a/packages/renderer/src/test/get-assets-for-markup.tsx b/packages/renderer/src/test/get-assets-for-markup.tsx
index d9526b3a5d..2c0dc39220 100644
--- a/packages/renderer/src/test/get-assets-for-markup.tsx
+++ b/packages/renderer/src/test/get-assets-for-markup.tsx
@@ -116,6 +116,7 @@ export const getAssetsForMarkup = async (
initialCanvasContent={null}
>
<Internals.RemotionRootContexts
+ _experimentalKeepAudioContextAlive={false}
frameState={null}
audioEnabled
videoEnabled
diff --git a/packages/shapes/src/test/test-utils.tsx b/packages/shapes/src/test/test-utils.tsx
index 0b9150415d..2033031b61 100644
--- a/packages/shapes/src/test/test-utils.tsx
+++ b/packages/shapes/src/test/test-utils.tsx
@@ -64,6 +64,7 @@ const AllTheProviders: FC<{
onlyRenderComposition="shape-test"
>
<Internals.RemotionRootContexts
+ _experimentalKeepAudioContextAlive={false}
audioEnabled
audioLatencyHint="interactive"
frameState={null}
diff --git a/packages/studio-server/src/preview-server/start-server.ts b/packages/studio-server/src/preview-server/start-server.ts
index f96467fe93..3fbd27e526 100644
--- a/packages/studio-server/src/preview-server/start-server.ts
+++ b/packages/studio-server/src/preview-server/start-server.ts
@@ -70,6 +70,7 @@ export const startServer = async (options: {
binariesDirectory: string | null;
forceIPv4: boolean;
getAudioLatencyHint: () => AudioContextLatencyCategory | null;
+ getExperimentalKeepAudioContextAlive: () => boolean;
getPreviewSampleRate: () => number | null;
enableCrossSiteIsolation: boolean;
forceNew: boolean;
@@ -179,6 +180,8 @@ export const startServer = async (options: {
gitSource: options.gitSource,
binariesDirectory: options.binariesDirectory,
getAudioLatencyHint: options.getAudioLatencyHint,
+ getExperimentalKeepAudioContextAlive:
+ options.getExperimentalKeepAudioContextAlive,
getPreviewSampleRate: options.getPreviewSampleRate,
enableCrossSiteIsolation: options.enableCrossSiteIsolation,
getStudioRuntimeConfig: options.getStudioRuntimeConfig,
diff --git a/packages/studio-server/src/routes.ts b/packages/studio-server/src/routes.ts
index 30a97e6b45..6609b25316 100644
--- a/packages/studio-server/src/routes.ts
+++ b/packages/studio-server/src/routes.ts
@@ -86,6 +86,7 @@ const handleFallback = async ({
getRenderDefaults,
getNumberOfAudioTags,
getAudioLatencyHint,
+ getExperimentalKeepAudioContextAlive,
getPreviewSampleRate,
gitSource,
logLevel,
@@ -104,6 +105,7 @@ const handleFallback = async ({
getRenderDefaults: () => RenderDefaults;
getNumberOfAudioTags: () => number;
getAudioLatencyHint: () => AudioContextLatencyCategory | null;
+ getExperimentalKeepAudioContextAlive: () => boolean;
getPreviewSampleRate: () => number | null;
gitSource: GitSource | null;
logLevel: LogLevel;
@@ -188,6 +190,7 @@ const handleFallback = async ({
logLevel,
mode: 'dev',
audioLatencyHint: getAudioLatencyHint() ?? 'playback',
+ experimentalKeepAudioContextAlive: getExperimentalKeepAudioContextAlive(),
sampleRate: getPreviewSampleRate(),
studioRuntimeConfig: getStudioRuntimeConfig(),
}),
@@ -381,6 +384,7 @@ export const handleRoutes = ({
gitSource,
binariesDirectory,
getAudioLatencyHint,
+ getExperimentalKeepAudioContextAlive,
getPreviewSampleRate,
enableCrossSiteIsolation,
getStudioRuntimeConfig,
@@ -408,6 +412,7 @@ export const handleRoutes = ({
gitSource: GitSource | null;
binariesDirectory: string | null;
getAudioLatencyHint: () => AudioContextLatencyCategory | null;
+ getExperimentalKeepAudioContextAlive: () => boolean;
getPreviewSampleRate: () => number | null;
enableCrossSiteIsolation: boolean;
getStudioRuntimeConfig: () => StudioRuntimeConfig;
@@ -589,6 +594,7 @@ export const handleRoutes = ({
gitSource,
logLevel,
getAudioLatencyHint,
+ getExperimentalKeepAudioContextAlive,
getPreviewSampleRate,
enableCrossSiteIsolation,
getStudioRuntimeConfig,
diff --git a/packages/studio-server/src/start-studio.ts b/packages/studio-server/src/start-studio.ts
index 6b1d3eb0da..bae43ea261 100644
--- a/packages/studio-server/src/start-studio.ts
+++ b/packages/studio-server/src/start-studio.ts
@@ -60,6 +60,7 @@ export const startStudio = async ({
binariesDirectory,
forceIPv4,
getAudioLatencyHint,
+ getExperimentalKeepAudioContextAlive,
getPreviewSampleRate,
enableCrossSiteIsolation,
forceNew,
@@ -87,6 +88,7 @@ export const startStudio = async ({
getRenderQueue: () => RenderJob[];
getNumberOfAudioTags: () => number;
getAudioLatencyHint: () => AudioContextLatencyCategory | null;
+ getExperimentalKeepAudioContextAlive: () => boolean;
getPreviewSampleRate: () => number | null;
enableCrossSiteIsolation: boolean;
queueMethods: QueueMethods;
@@ -173,6 +175,7 @@ export const startStudio = async ({
binariesDirectory,
forceIPv4,
getAudioLatencyHint,
+ getExperimentalKeepAudioContextAlive,
getPreviewSampleRate,
enableCrossSiteIsolation,
forceNew,
diff --git a/packages/studio-server/src/test/file-source-route.test.ts b/packages/studio-server/src/test/file-source-route.test.ts
index 578742d2c1..bae8ed241d 100644
--- a/packages/studio-server/src/test/file-source-route.test.ts
+++ b/packages/studio-server/src/test/file-source-route.test.ts
@@ -73,6 +73,7 @@ test('serves file source from an origin-less GET request', async () => {
enableCrossSiteIsolation: false,
entryPoint: '',
getAudioLatencyHint: () => null,
+ getExperimentalKeepAudioContextAlive: () => false,
getCurrentInputProps: () => ({}),
getDefaultCodingAgent: () => null,
getDefaultEditor: () => null,
diff --git a/packages/studio-shared/src/config-method-lifecycles.ts b/packages/studio-shared/src/config-method-lifecycles.ts
index af84178b3a..d26c77eef6 100644
--- a/packages/studio-shared/src/config-method-lifecycles.ts
+++ b/packages/studio-shared/src/config-method-lifecycles.ts
@@ -47,6 +47,7 @@ export const configMethodLifecycles = {
setEnforceAudioTrack: 'runtime',
setEntryPoint: 'restart',
setEveryNthFrame: 'runtime',
+ setExperimentalKeepAudioContextAlive: 'reload',
setExperimentalRspackEnabled: 'restart',
setForSeamlessAacConcatenation: 'runtime',
setForceNewStudioEnabled: 'restart',
diff --git a/packages/studio-shared/src/studio-html.ts b/packages/studio-shared/src/studio-html.ts
index 303327920f..94e4134db0 100644
--- a/packages/studio-shared/src/studio-html.ts
+++ b/packages/studio-shared/src/studio-html.ts
@@ -17,6 +17,7 @@ export type StudioHtmlOptions = {
completedClientRenders?: unknown | null;
numberOfAudioTags: number;
audioLatencyHint: AudioContextLatencyCategory;
+ experimentalKeepAudioContextAlive: boolean;
sampleRate: number | null;
publicFiles: StaticFile[];
publicFolderExists: string | null;
@@ -57,6 +58,7 @@ export const studioHtml = ({
installedDependencies,
packageManager,
audioLatencyHint,
+ experimentalKeepAudioContextAlive,
sampleRate,
logLevel,
mode,
@@ -93,6 +95,7 @@ export const studioHtml = ({
<body>
<script>window.remotion_numberOfAudioTags = ${numberOfAudioTags};</script>
<script>window.remotion_audioLatencyHint = "${audioLatencyHint}";</script>
+ <script>window.remotion_experimentalKeepAudioContextAlive = ${experimentalKeepAudioContextAlive};</script>
<script>window.remotion_sampleRate = ${sampleRate};</script>
<script>window.remotion_previewSampleRate = ${sampleRate};</script>
${mode === 'dev' ? `<script>window.remotion_logLevel = "${logLevel}";</script>` : ''}
diff --git a/packages/studio-shared/src/test/studio-html.test.ts b/packages/studio-shared/src/test/studio-html.test.ts
index 2d3f9c0f00..0dfb7bbec1 100644
--- a/packages/studio-shared/src/test/studio-html.test.ts
+++ b/packages/studio-shared/src/test/studio-html.test.ts
@@ -20,6 +20,7 @@ const makeHtml = ({
renderQueue: null,
numberOfAudioTags: 0,
audioLatencyHint: 'playback',
+ experimentalKeepAudioContextAlive: true,
sampleRate: 48000,
publicFiles: [
{
@@ -52,6 +53,9 @@ test('makes relative bundles resolve public assets from the document URL', () =>
expect(html).toContain('href="./favicon.ico"');
expect(html).toContain('src="./bundle.js"');
+ expect(html).toContain(
+ 'window.remotion_experimentalKeepAudioContextAlive = true;',
+ );
expect(html).toContain(
'window.remotion_staticBase = new URL("./public", window.location.href).pathname;',
);
diff --git a/packages/studio/src/Studio.tsx b/packages/studio/src/Studio.tsx
index bbaf7c4dae..728d5fe271 100644
--- a/packages/studio/src/Studio.tsx
+++ b/packages/studio/src/Studio.tsx
@@ -9,6 +9,12 @@ import {FastRefreshProvider} from './FastRefreshProvider';
import {injectCSS} from './helpers/inject-css';
import {ResolveCompositionConfigInStudio} from './ResolveCompositionConfigInStudio';
+declare global {
+ interface Window {
+ remotion_experimentalKeepAudioContextAlive: boolean | undefined;
+ }
+}
+
const getServerDisconnectedDomElement = () => {
return document.getElementById('server-disconnected-overlay');
};
@@ -32,6 +38,9 @@ const StudioInner: React.FC<{
numberOfAudioTags={window.remotion_numberOfAudioTags}
audioLatencyHint={window.remotion_audioLatencyHint ?? 'playback'}
previewSampleRate={window.remotion_previewSampleRate}
+ _experimentalKeepAudioContextAlive={
+ window.remotion_experimentalKeepAudioContextAlive ?? false
+ }
>
<StaticFilesProvider>
<ResolveCompositionConfigInStudio>
diff --git a/packages/studio/src/renderEntry.tsx b/packages/studio/src/renderEntry.tsx
index 1f3cd51449..600e024620 100644
--- a/packages/studio/src/renderEntry.tsx
+++ b/packages/studio/src/renderEntry.tsx
@@ -253,6 +253,7 @@ const renderContent = (Root: React.FC) => {
numberOfAudioTags={0}
audioLatencyHint={window.remotion_audioLatencyHint ?? 'playback'}
previewSampleRate={window.remotion_previewSampleRate}
+ _experimentalKeepAudioContextAlive={false}
>
<Internals.RenderAssetManagerProvider collectAssets={null}>
<Root />
@@ -281,6 +282,7 @@ const renderContent = (Root: React.FC) => {
numberOfAudioTags={0}
audioLatencyHint={window.remotion_audioLatencyHint ?? 'playback'}
previewSampleRate={window.remotion_previewSampleRate}
+ _experimentalKeepAudioContextAlive={false}
>
<Internals.RenderAssetManagerProvider collectAssets={null}>
<Root />
diff --git a/packages/web-renderer/src/update-time.tsx b/packages/web-renderer/src/update-time.tsx
index 9881abfa8f..96cc75d516 100644
--- a/packages/web-renderer/src/update-time.tsx
+++ b/packages/web-renderer/src/update-time.tsx
@@ -36,6 +36,7 @@ export const UpdateTime: React.FC<{
return (
<Internals.RemotionRootContexts
+ _experimentalKeepAudioContextAlive={false}
audioEnabled={audioEnabled}
videoEnabled={videoEnabled}
logLevel={logLevel}