Skip to content

🎥 Make videos programmatically with React

very nice! it works

Jonny Burger8d89daa13b15
diff --git a/packages/media-utils/eslint.config.mjs b/packages/media-utils/eslint.config.mjs
index 04fd4fac11..ab29acaba0 100644
--- a/packages/media-utils/eslint.config.mjs
+++ b/packages/media-utils/eslint.config.mjs
@@ -1,6 +1,6 @@
import {remotionFlatConfig} from '@remotion/eslint-config-internal';
-const config = remotionFlatConfig({react: false});
+const config = remotionFlatConfig({react: true});
export default {
...config,
diff --git a/packages/media-utils/src/get-partial-wave-data.ts b/packages/media-utils/src/get-partial-wave-data.ts
index 0c036a4d67..49bc13217a 100644
--- a/packages/media-utils/src/get-partial-wave-data.ts
+++ b/packages/media-utils/src/get-partial-wave-data.ts
@@ -48,7 +48,7 @@ export const getPartialWaveData = async ({
const arrayBuffer = await response.arrayBuffer();
const uintArray = new Uint8Array(arrayBuffer);
- const samples = [];
+ const samples = new Float32Array(uintArray.length / blockAlign);
for (let i = 0; i < uintArray.length; i += blockAlign) {
const sampleStart = i + channelIndex * (bitsPerSample / 8);
@@ -62,7 +62,7 @@ export const getPartialWaveData = async ({
throw new Error(`Unsupported bits per sample: ${bitsPerSample}`);
}
- samples.push(sample);
+ samples[i / blockAlign] = sample;
}
return samples;
diff --git a/packages/media-utils/src/index.ts b/packages/media-utils/src/index.ts
index ef3178cb77..0d3935f543 100644
--- a/packages/media-utils/src/index.ts
+++ b/packages/media-utils/src/index.ts
@@ -8,8 +8,9 @@ export {getImageDimensions} from './get-image-dimensions';
export {getPartialWaveData} from './get-partial-wave-data';
export {getVideoMetadata} from './get-video-metadata';
export {getWaveformPortion} from './get-waveform-portion';
-export {probeWaveFile} from './probe-wave-file';
+export {WaveProbe, probeWaveFile} from './probe-wave-file';
export * from './types';
export type {AudioData, VideoMetadata as VideoData} from './types';
export {useAudioData} from './use-audio-data';
-export {visualizeAudio} from './visualize-audio';
+export {useWindowedAudioData} from './use-windowed-audio-data';
+export {VisualizeAudioOptions, visualizeAudio} from './visualize-audio';
diff --git a/packages/media-utils/src/probe-wave-file.ts b/packages/media-utils/src/probe-wave-file.ts
index 819bcf1f38..50d7924857 100644
--- a/packages/media-utils/src/probe-wave-file.ts
+++ b/packages/media-utils/src/probe-wave-file.ts
@@ -36,7 +36,17 @@ export const getInt8AsFloat = (bytes: Uint8Array, offset: number) => {
return (bytes[offset] - 128) / 128;
};
-export const probeWaveFile = async (src: string) => {
+export type WaveProbe = {
+ dataOffset: number;
+ bitsPerSample: number;
+ numberOfChannels: number;
+ sampleRate: number;
+ blockAlign: number;
+ fileSize: number;
+ durationInSeconds: number;
+};
+
+export const probeWaveFile = async (src: string): Promise<WaveProbe> => {
const response = await fetchWithCorsCatch(src, {
headers: {
range: 'bytes=0-256',
@@ -126,5 +136,6 @@ export const probeWaveFile = async (src: string) => {
sampleRate,
blockAlign,
fileSize: size,
+ durationInSeconds: dataSize / (sampleRate * blockAlign),
};
};
diff --git a/packages/media-utils/src/use-windowed-audio-data.ts b/packages/media-utils/src/use-windowed-audio-data.ts
new file mode 100644
index 0000000000..a1d304f567
--- /dev/null
+++ b/packages/media-utils/src/use-windowed-audio-data.ts
@@ -0,0 +1,156 @@
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
+import {cancelRender, continueRender, delayRender} from 'remotion';
+import {getPartialWaveData} from './get-partial-wave-data';
+import {isRemoteAsset} from './is-remote-asset';
+import type {WaveProbe} from './probe-wave-file';
+import {probeWaveFile} from './probe-wave-file';
+import type {AudioData} from './types';
+
+type WaveformMap = Record<number, AudioData>;
+
+export type UseWindowedAudioDataOptions = {
+ src: string;
+ frame: number;
+ fps: number;
+ windowInSeconds: number;
+ channelIndex?: number;
+};
+
+export type UseWindowedAudioDataReturnValue = {
+ audioData: AudioData | null;
+ dataOffsetInSeconds: number;
+};
+
+export const useWindowedAudioData = ({
+ src,
+ frame,
+ fps,
+ windowInSeconds,
+ channelIndex = 0,
+}: UseWindowedAudioDataOptions): UseWindowedAudioDataReturnValue => {
+ const isMounted = useRef(true);
+ const [waveProbe, setWaveProbe] = useState<WaveProbe | null>(null);
+ const [waveFormMap, setWaveformMap] = useState({} as WaveformMap);
+ const [initialWindowInSeconds] = useState(windowInSeconds);
+ if (windowInSeconds !== initialWindowInSeconds) {
+ throw new Error('windowInSeconds cannot be changed dynamically');
+ }
+
+ useEffect(() => {
+ isMounted.current = true;
+
+ return () => {
+ isMounted.current = false;
+ };
+ }, []);
+
+ const fetchMetadata = useCallback(async () => {
+ const handle = delayRender(
+ `Waiting for audio metadata with src="${src}" to be loaded`,
+ );
+
+ try {
+ const data = await probeWaveFile(src);
+ if (isMounted.current) {
+ setWaveProbe(data);
+ }
+
+ continueRender(handle);
+ } catch (err) {
+ cancelRender(err);
+ }
+ }, [src]);
+
+ useLayoutEffect(() => {
+ fetchMetadata();
+ }, [fetchMetadata]);
+
+ const currentTime = frame / fps;
+ const currentWindowIndex = Math.floor(currentTime / windowInSeconds);
+
+ const windowsToFetch = useMemo(() => {
+ return [
+ currentWindowIndex,
+ currentWindowIndex - 1,
+ currentWindowIndex + 1,
+ ].filter((i) => i >= 0);
+ }, [currentWindowIndex]);
+
+ const fetchAndSetWaveformData = useCallback(
+ async (windowIndex: number) => {
+ if (!waveProbe) {
+ throw new Error('Wave probe is not loaded yet');
+ }
+
+ const partialWaveData = await getPartialWaveData({
+ bitsPerSample: waveProbe.bitsPerSample,
+ blockAlign: waveProbe.blockAlign,
+ channelIndex,
+ dataOffset: waveProbe.dataOffset,
+ fileSize: waveProbe.fileSize,
+ fromSeconds: windowIndex * windowInSeconds,
+ sampleRate: waveProbe.sampleRate,
+ src,
+ toSeconds: (windowIndex + 1) * windowInSeconds,
+ });
+
+ setWaveformMap((prev) => {
+ const entries = Object.keys(prev);
+ const windowsToClear = entries.filter(
+ (entry) => !windowsToFetch.includes(Number(entry)),
+ );
+ return {
+ ...prev,
+ // Delete windows that are not needed anymore
+ ...windowsToClear.reduce(
+ (acc, key) => {
+ acc[key] = null;
+ return acc;
+ },
+ {} as Record<string, null>,
+ ),
+ // Add the new window
+ [windowIndex]: {
+ channelWaveforms: [partialWaveData],
+ durationInSeconds: waveProbe.durationInSeconds,
+ isRemote: isRemoteAsset(src),
+ numberOfChannels: 1,
+ resultId: String(Math.random()),
+ sampleRate: waveProbe.sampleRate,
+ },
+ };
+ });
+ },
+ [channelIndex, src, waveProbe, windowInSeconds, windowsToFetch],
+ );
+
+ useEffect(() => {
+ if (!waveProbe) {
+ return;
+ }
+
+ Promise.all(
+ windowsToFetch.map((windowIndex) => {
+ return fetchAndSetWaveformData(windowIndex);
+ }),
+ ).catch((err) => {
+ cancelRender(err);
+ });
+ }, [fetchAndSetWaveformData, waveProbe, windowsToFetch]);
+
+ const currentAudioData = useMemo(() => {
+ return waveFormMap[currentWindowIndex] ?? null;
+ }, [currentWindowIndex, waveFormMap]);
+
+ return {
+ audioData: currentAudioData,
+ dataOffsetInSeconds: currentWindowIndex * windowInSeconds,
+ };
+};
diff --git a/packages/template-audiogram/src/Audiogram/Waveform.tsx b/packages/template-audiogram/src/Audiogram/Waveform.tsx
index 066cb0e406..747f434a60 100644
--- a/packages/template-audiogram/src/Audiogram/Waveform.tsx
+++ b/packages/template-audiogram/src/Audiogram/Waveform.tsx
@@ -1,10 +1,4 @@
-import {
- getPartialWaveData,
- probeWaveFile,
- useAudioData,
- visualizeAudio,
-} from "@remotion/media-utils";
-import { useEffect } from "react";
+import { useWindowedAudioData, visualizeAudio } from "@remotion/media-utils";
import { useCurrentFrame, useVideoConfig } from "remotion";
export const Waveform: React.FC<{
@@ -25,30 +19,12 @@ export const Waveform: React.FC<{
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
- useEffect(() => {
- probeWaveFile(audioSrc)
- .then((result) => {
- return getPartialWaveData({
- bitsPerSample: result.bitsPerSample,
- blockAlign: result.blockAlign,
- dataOffset: result.dataOffset,
- fileSize: result.fileSize,
- fromSeconds: 0,
- sampleRate: result.sampleRate,
- src: audioSrc,
- toSeconds: 1,
- channelIndex: 0,
- });
- })
- .then((data) => {
- console.log(data);
- })
- .catch((err) => {
- console.log(err);
- });
- }, [audioSrc]);
-
- const audioData = useAudioData(audioSrc);
+ const { audioData, dataOffsetInSeconds } = useWindowedAudioData({
+ src: audioSrc,
+ fps,
+ frame,
+ windowInSeconds: 10,
+ });
if (!audioData) {
return null;
@@ -60,6 +36,7 @@ export const Waveform: React.FC<{
audioData,
numberOfSamples, // Use more samples to get a nicer visualisation
optimizeFor: "speed",
+ dataOffsetInSeconds,
});
// Pick the low values because they look nicer than high values