Skip to content

🎥 Make videos programmatically with React

`remotion`: Fix `useLayoutEffect does nothing on the server` warning from audio context

Jonny Burger12c604c95bbb
diff --git a/packages/core/src/use-amplification.ts b/packages/core/src/use-amplification.ts
index d82b990744..3e91944113 100644
--- a/packages/core/src/use-amplification.ts
+++ b/packages/core/src/use-amplification.ts
@@ -60,51 +60,54 @@ export const useVolume = ({
const {audioContext} = sharedAudioContext;
- useLayoutEffect(() => {
- if (!audioContext) {
- return;
- }
-
- if (!mediaRef.current) {
- return;
- }
-
- if (!shouldUseWebAudioApi) {
- return;
- }
-
- // [1]
- if (mediaRef.current.playbackRate !== 1 && isSafari()) {
- warnSafariOnce(logLevel);
- return;
- }
-
- if (!source) {
- return;
- }
-
- const gainNode = new GainNode(audioContext, {
- gain: currentVolumeRef.current,
- });
+ if (typeof window !== 'undefined') {
+ // eslint-disable-next-line react-hooks/rules-of-hooks
+ useLayoutEffect(() => {
+ if (!audioContext) {
+ return;
+ }
+
+ if (!mediaRef.current) {
+ return;
+ }
+
+ if (!shouldUseWebAudioApi) {
+ return;
+ }
+
+ // [1]
+ if (mediaRef.current.playbackRate !== 1 && isSafari()) {
+ warnSafariOnce(logLevel);
+ return;
+ }
+
+ if (!source) {
+ return;
+ }
+
+ const gainNode = new GainNode(audioContext, {
+ gain: currentVolumeRef.current,
+ });
+
+ source.attemptToConnect();
+ source.get().connect(gainNode);
+ gainNode.connect(audioContext.destination);
+ audioStuffRef.current = {
+ gainNode,
+ };
- source.attemptToConnect();
- source.get().connect(gainNode);
- gainNode.connect(audioContext.destination);
- audioStuffRef.current = {
- gainNode,
- };
-
- Log.trace(
- logLevel,
- `Starting to amplify ${mediaRef.current?.src}. Gain = ${currentVolumeRef.current}, playbackRate = ${mediaRef.current?.playbackRate}`,
- );
+ Log.trace(
+ logLevel,
+ `Starting to amplify ${mediaRef.current?.src}. Gain = ${currentVolumeRef.current}, playbackRate = ${mediaRef.current?.playbackRate}`,
+ );
- return () => {
- audioStuffRef.current = null;
- gainNode.disconnect();
- source.get().disconnect();
- };
- }, [logLevel, mediaRef, audioContext, source, shouldUseWebAudioApi]);
+ return () => {
+ audioStuffRef.current = null;
+ gainNode.disconnect();
+ source.get().disconnect();
+ };
+ }, [logLevel, mediaRef, audioContext, source, shouldUseWebAudioApi]);
+ }
if (audioStuffRef.current) {
const valueToSet = volume;