Skip to content

πŸŽ₯ Make videos programmatically with React

windowed audio data

Jonny Burger7ac3084c172c
diff --git a/packages/media-utils/src/fetch-with-cors-catch.ts b/packages/media-utils/src/fetch-with-cors-catch.ts
new file mode 100644
index 0000000000..fbc006e753
--- /dev/null
+++ b/packages/media-utils/src/fetch-with-cors-catch.ts
@@ -0,0 +1,26 @@
+export const fetchWithCorsCatch = async (src: string, init?: RequestInit) => {
+ try {
+ const response = await fetch(src, {
+ mode: 'cors',
+ referrerPolicy: 'no-referrer-when-downgrade',
+ ...init,
+ });
+ return response;
+ } catch (err) {
+ const error = err as Error;
+ if (
+ // Chrome
+ error.message.includes('Failed to fetch') ||
+ // Safari
+ error.message.includes('Load failed') ||
+ // Firefox
+ error.message.includes('NetworkError when attempting to fetch resource')
+ ) {
+ throw new TypeError(
+ `Failed to read from ${src}: ${error.message}. Does the resource support CORS?`,
+ );
+ }
+
+ throw err;
+ }
+};
diff --git a/packages/media-utils/src/get-audio-data.ts b/packages/media-utils/src/get-audio-data.ts
index 4959a1fc08..a06deeeb7f 100644
--- a/packages/media-utils/src/get-audio-data.ts
+++ b/packages/media-utils/src/get-audio-data.ts
@@ -1,3 +1,4 @@
+import {fetchWithCorsCatch} from './fetch-with-cors-catch';
import {isRemoteAsset} from './is-remote-asset';
import {pLimit} from './p-limit';
import type {AudioData} from './types';
@@ -6,32 +7,6 @@ const metadataCache: {[key: string]: AudioData} = {};
const limit = pLimit(3);
-const fetchWithCorsCatch = async (src: string) => {
- try {
- const response = await fetch(src, {
- mode: 'cors',
- referrerPolicy: 'no-referrer-when-downgrade',
- });
- return response;
- } catch (err) {
- const error = err as Error;
- if (
- // Chrome
- error.message.includes('Failed to fetch') ||
- // Safari
- error.message.includes('Load failed') ||
- // Firefox
- error.message.includes('NetworkError when attempting to fetch resource')
- ) {
- throw new TypeError(
- `Failed to read from ${src}: ${error.message}. Does the resource support CORS?`,
- );
- }
-
- throw err;
- }
-};
-
type Options = {
sampleRate?: number;
};
@@ -46,7 +21,7 @@ const fn = async (src: string, options?: Options): Promise<AudioData> => {
}
const audioContext = new AudioContext({
- sampleRate: options?.sampleRate ?? 48000,
+ sampleRate: options?.sampleRate ?? 16000,
});
const response = await fetchWithCorsCatch(src);
diff --git a/packages/media-utils/src/get-partial-wave-data.ts b/packages/media-utils/src/get-partial-wave-data.ts
new file mode 100644
index 0000000000..0c036a4d67
--- /dev/null
+++ b/packages/media-utils/src/get-partial-wave-data.ts
@@ -0,0 +1,69 @@
+import {fetchWithCorsCatch} from './fetch-with-cors-catch';
+import {getInt16AsFloat, getInt8AsFloat} from './probe-wave-file';
+
+export const getPartialWaveData = async ({
+ dataOffset,
+ src,
+ bitsPerSample,
+ channelIndex,
+ sampleRate,
+ fromSeconds,
+ toSeconds,
+ blockAlign,
+ fileSize,
+}: {
+ dataOffset: number;
+ src: string;
+ bitsPerSample: number;
+ channelIndex: number;
+ sampleRate: number;
+ fromSeconds: number;
+ toSeconds: number;
+ blockAlign: number;
+ fileSize: number;
+}) => {
+ const startByte =
+ dataOffset + Math.floor(fromSeconds * sampleRate) * blockAlign;
+ const endByte =
+ dataOffset + Math.floor(toSeconds * sampleRate - 1) * blockAlign;
+
+ if (endByte > fileSize - 1) {
+ throw new Error(
+ `End byte ${endByte} is greater than file size ${fileSize}`,
+ );
+ }
+
+ const response = await fetchWithCorsCatch(src, {
+ headers: {
+ range: `bytes=${startByte}-${endByte}`,
+ },
+ });
+
+ if (response.status !== 206) {
+ throw new Error(
+ `Tried to read bytes ${startByte}-${endByte} from ${src}, but the response status code was not 206. This means the server might not support returning a partial response.`,
+ );
+ }
+
+ const arrayBuffer = await response.arrayBuffer();
+ const uintArray = new Uint8Array(arrayBuffer);
+
+ const samples = [];
+
+ for (let i = 0; i < uintArray.length; i += blockAlign) {
+ const sampleStart = i + channelIndex * (bitsPerSample / 8);
+
+ let sample;
+ if (bitsPerSample === 16) {
+ sample = getInt16AsFloat(uintArray, sampleStart);
+ } else if (bitsPerSample === 8) {
+ sample = getInt8AsFloat(uintArray, sampleStart);
+ } else {
+ throw new Error(`Unsupported bits per sample: ${bitsPerSample}`);
+ }
+
+ samples.push(sample);
+ }
+
+ return samples;
+};
diff --git a/packages/media-utils/src/index.ts b/packages/media-utils/src/index.ts
index af9c25a981..ef3178cb77 100644
--- a/packages/media-utils/src/index.ts
+++ b/packages/media-utils/src/index.ts
@@ -5,8 +5,10 @@ export {
getAudioDurationInSeconds,
} from './get-audio-duration-in-seconds';
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 * from './types';
export type {AudioData, VideoMetadata as VideoData} from './types';
export {useAudioData} from './use-audio-data';
diff --git a/packages/media-utils/src/probe-wave-file.ts b/packages/media-utils/src/probe-wave-file.ts
new file mode 100644
index 0000000000..819bcf1f38
--- /dev/null
+++ b/packages/media-utils/src/probe-wave-file.ts
@@ -0,0 +1,130 @@
+import {fetchWithCorsCatch} from './fetch-with-cors-catch';
+
+const getUint32 = (bytes: Uint8Array, offset: number) => {
+ const val1 = bytes[offset + 3];
+ const val2 = bytes[offset + 2];
+ const val3 = bytes[offset + 1];
+ const val4 = bytes[offset];
+ return (val1 << 24) | (val2 << 16) | (val3 << 8) | val4;
+};
+
+const getUint16 = (bytes: Uint8Array, offset: number) => {
+ const val1 = bytes[offset + 1];
+ const val2 = bytes[offset];
+ return (val1 << 8) | val2;
+};
+
+export const getInt16AsFloat = (bytes: Uint8Array, offset: number) => {
+ if (offset >= bytes.length) {
+ throw new Error(
+ `Tried to read a 16-bit integer from offset ${offset} but the array length is ${bytes.length}`,
+ );
+ }
+
+ const val1 = bytes[offset + 1];
+ const val2 = bytes[offset];
+ return ((val1 << 8) | val2) / 32768;
+};
+
+export const getInt8AsFloat = (bytes: Uint8Array, offset: number) => {
+ if (offset >= bytes.length) {
+ throw new Error(
+ `Tried to read an 8-bit integer from offset ${offset} but the array length is ${bytes.length}`,
+ );
+ }
+
+ return (bytes[offset] - 128) / 128;
+};
+
+export const probeWaveFile = async (src: string) => {
+ const response = await fetchWithCorsCatch(src, {
+ headers: {
+ range: 'bytes=0-256',
+ },
+ });
+ if (response.status !== 206) {
+ throw new Error(
+ `Tried to read bytes 0-256 from ${src}, but the response status code was not 206. This means the server might not support returning a partial response.`,
+ );
+ }
+
+ const buffer = await response.arrayBuffer();
+ const uintArray = new Uint8Array(buffer);
+
+ // const header = uintArray.slice(0, 44);
+
+ const shouldBeRiff = new TextDecoder().decode(uintArray.slice(0, 4));
+ if (shouldBeRiff !== 'RIFF') {
+ throw new Error(
+ 'getPartialAudioData() requires a WAVE file, but the first bytes are not RIFF. ',
+ );
+ }
+
+ const size = getUint32(uintArray, 4);
+ const shouldBeWAVE = new TextDecoder().decode(uintArray.slice(8, 12));
+ if (shouldBeWAVE !== 'WAVE') {
+ throw new Error(
+ 'getPartialAudioData() requires a WAVE file, but the bytes 8-11 are not "WAVE". ',
+ );
+ }
+
+ const shouldBeFmt = new TextDecoder().decode(uintArray.slice(12, 16));
+ if (shouldBeFmt !== 'fmt ') {
+ throw new Error(
+ 'getPartialAudioData() requires a WAVE file, but the bytes 12-15 are not "fmt ". ',
+ );
+ }
+
+ // const chunkSize = toUint32(uintArray.slice(16, 20));
+ const audioFormat = getUint16(uintArray, 20);
+ if (audioFormat !== 1) {
+ throw new Error(
+ 'getPartialAudioData() supports only a WAVE file with PCM audio format, but the audio format is not PCM. ',
+ );
+ }
+
+ const numberOfChannels = getUint16(uintArray, 22);
+ const sampleRate = getUint32(uintArray, 24);
+ // const byteRate = toUint32(uintArray.slice(28, 32));
+ const blockAlign = getUint16(uintArray, 32);
+ const bitsPerSample = getUint16(uintArray, 34);
+ let offset = 36;
+ const shouldBeDataOrList = new TextDecoder().decode(
+ uintArray.slice(offset, offset + 4),
+ );
+
+ if (shouldBeDataOrList === 'LIST') {
+ const listSize = getUint32(uintArray, 40);
+ offset += listSize;
+ offset += 8;
+ }
+
+ const shouldBeData = new TextDecoder().decode(
+ uintArray.slice(offset, offset + 4),
+ );
+
+ if (shouldBeData !== 'data') {
+ throw new Error(
+ 'getPartialAudioData() requires a WAVE file, but the bytes 36-39 are not "data". ',
+ );
+ }
+
+ const dataSize = getUint32(uintArray, offset + 4);
+
+ if (dataSize + offset !== size) {
+ throw new Error(
+ `getPartialAudioData() requires a WAVE file, but: Expected ${
+ dataSize + offset
+ }, got ${size}. `,
+ );
+ }
+
+ return {
+ dataOffset: offset + 8,
+ bitsPerSample,
+ numberOfChannels,
+ sampleRate,
+ blockAlign,
+ fileSize: size,
+ };
+};
diff --git a/packages/template-audiogram/src/Audiogram/Captions.tsx b/packages/template-audiogram/src/Audiogram/Captions.tsx
index 6710205da7..ed00c29e41 100644
--- a/packages/template-audiogram/src/Audiogram/Captions.tsx
+++ b/packages/template-audiogram/src/Audiogram/Captions.tsx
@@ -54,8 +54,6 @@ export const PaginatedCaptions: React.FC<{
});
const currentScale = useCurrentScale();
- console.log(captions);
-
const [lineOffset, setLineOffset] = useState(0);
const currentAndFollowingSentences = useMemo(() => {
diff --git a/packages/template-audiogram/src/Audiogram/Waveform.tsx b/packages/template-audiogram/src/Audiogram/Waveform.tsx
index 9658e32709..066cb0e406 100644
--- a/packages/template-audiogram/src/Audiogram/Waveform.tsx
+++ b/packages/template-audiogram/src/Audiogram/Waveform.tsx
@@ -1,4 +1,10 @@
-import { useAudioData, visualizeAudio } from "@remotion/media-utils";
+import {
+ getPartialWaveData,
+ probeWaveFile,
+ useAudioData,
+ visualizeAudio,
+} from "@remotion/media-utils";
+import { useEffect } from "react";
import { useCurrentFrame, useVideoConfig } from "remotion";
export const Waveform: React.FC<{
@@ -19,6 +25,29 @@ 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);
if (!audioData) {
diff --git a/packages/template-audiogram/src/Root.tsx b/packages/template-audiogram/src/Root.tsx
index 53e9a3e9da..bcb8b674c2 100644
--- a/packages/template-audiogram/src/Root.tsx
+++ b/packages/template-audiogram/src/Root.tsx
@@ -19,7 +19,7 @@ export const RemotionRoot: React.FC = () => {
audioOffsetInSeconds: 6.9,
// Title settings
- audioFileName: staticFile("audio1.mp3"),
+ audioFileName: staticFile("audio2.wav"),
coverImgFileName: staticFile("cover.jpg"),
titleText:
"#234 – Money, Kids, and Choosing Your Market with Justin Jackson of Transistor.fm",