Skip to content

🎥 Make videos programmatically with React

smoothen + docs

Jonny Burger81ceeeb96a65
diff --git a/packages/docs/components/AudioWaveformExamples.tsx b/packages/docs/components/AudioWaveformExamples.tsx
new file mode 100644
index 0000000000..a4aeb82602
--- /dev/null
+++ b/packages/docs/components/AudioWaveformExamples.tsx
@@ -0,0 +1,177 @@
+import { Player } from "@remotion/player";
+import {
+ createSmoothSvgPath,
+ useAudioData,
+ visualizeAudioWaveform,
+} from "@remotion/media-utils";
+import React from "react";
+import { AbsoluteFill, Audio, useCurrentFrame, useVideoConfig } from "remotion";
+import voice from "./voice-short.mp3";
+
+const BaseExample: React.FC = () => {
+ const frame = useCurrentFrame();
+ const { fps } = useVideoConfig();
+ const audioDataVoice = useAudioData(voice);
+ const { width, height } = useVideoConfig();
+
+ if (!audioDataVoice) {
+ return null;
+ }
+
+ const waveform = visualizeAudioWaveform({
+ fps,
+ frame,
+ audioData: audioDataVoice,
+ numberOfSamples: 32,
+ windowInSeconds: 1 / fps,
+ });
+
+ const p = createSmoothSvgPath(
+ waveform.map((x, i) => {
+ return [
+ (i / (waveform.length - 1)) * width,
+ (x - 0.5) * 300 + height / 2,
+ ];
+ })
+ );
+
+ return (
+ <div style={{ flex: 1 }}>
+ <Audio src={voice} />
+ <AbsoluteFill style={{ justifyContent: "center", alignItems: "center" }}>
+ <svg
+ style={{ backgroundColor: " #0B84F3" }}
+ viewBox={`0 0 ${width} ${height}`}
+ width={width}
+ height={height}
+ >
+ <path stroke="white" fill="none" strokeWidth={10} d={p as string} />
+ </svg>
+ </AbsoluteFill>
+ </div>
+ );
+};
+
+const MovingExample: React.FC = () => {
+ const frame = useCurrentFrame();
+ const { fps } = useVideoConfig();
+ const audioDataVoice = useAudioData(voice);
+ const { width, height } = useVideoConfig();
+
+ if (!audioDataVoice) {
+ return null;
+ }
+
+ const waveform = visualizeAudioWaveform({
+ fps,
+ frame,
+ audioData: audioDataVoice,
+ numberOfSamples: 32,
+ windowInSeconds: 10 / fps,
+ });
+
+ const p = createSmoothSvgPath(
+ waveform.map((x, i) => {
+ return [
+ (i / (waveform.length - 1)) * width,
+ (x - 0.5) * 300 + height / 2,
+ ];
+ })
+ );
+
+ return (
+ <div style={{ flex: 1 }}>
+ <Audio src={voice} />
+ <AbsoluteFill style={{ justifyContent: "center", alignItems: "center" }}>
+ <svg
+ style={{ backgroundColor: "#0B84F3" }}
+ viewBox={`0 0 ${width} ${height}`}
+ width={width}
+ height={height}
+ >
+ <path stroke="#ffffff" fill="none" strokeWidth={10} d={p as string} />
+ </svg>
+ </AbsoluteFill>
+ </div>
+ );
+};
+
+const PosterizedExample: React.FC = () => {
+ const frame = useCurrentFrame();
+ const { fps } = useVideoConfig();
+ const audioDataVoice = useAudioData(voice);
+ const { width, height } = useVideoConfig();
+
+ if (!audioDataVoice) {
+ return null;
+ }
+
+ const waveform = visualizeAudioWaveform({
+ fps,
+ frame: Math.round(frame / 3) * 3,
+ audioData: audioDataVoice,
+ numberOfSamples: 16,
+ windowInSeconds: 1 / fps,
+ });
+
+ const p = createSmoothSvgPath(
+ waveform.map((x, i) => {
+ return [
+ (i / (waveform.length - 1)) * width,
+ (x - 0.5) * 300 + height / 2,
+ ];
+ })
+ );
+
+ return (
+ <div style={{ flex: 1 }}>
+ <Audio src={voice} />
+ <AbsoluteFill style={{ justifyContent: "center", alignItems: "center" }}>
+ <svg
+ style={{ backgroundColor: " #0B84F3" }}
+ viewBox={`0 0 ${width} ${height}`}
+ width={width}
+ height={height}
+ >
+ <path stroke="white" fill="none" strokeWidth={10} d={p as string} />
+ </svg>
+ </AbsoluteFill>
+ </div>
+ );
+};
+
+export const AudioWaveFormExample: React.FC<{
+ type: "base" | "moving" | "posterized";
+}> = ({ type }) => {
+ const component = (() => {
+ if (type === "base") {
+ return BaseExample;
+ }
+
+ if (type === "moving") {
+ return MovingExample;
+ }
+
+ if (type === "posterized") {
+ return PosterizedExample;
+ }
+
+ throw new TypeError("oops");
+ })();
+ return (
+ <div>
+ <Player
+ component={component}
+ compositionWidth={2160}
+ compositionHeight={1080}
+ controls
+ durationInFrames={300}
+ fps={30}
+ style={{
+ width: "100%",
+ }}
+ loop
+ />
+ </div>
+ );
+};
diff --git a/packages/docs/components/voice-short.mp3 b/packages/docs/components/voice-short.mp3
new file mode 100644
index 0000000000..33b56ef741
Binary files /dev/null and b/packages/docs/components/voice-short.mp3 differ
diff --git a/packages/docs/docs/visualize-audio-waveform.md b/packages/docs/docs/visualize-audio-waveform.md
index 68ce4e78ab..443c929556 100644
--- a/packages/docs/docs/visualize-audio-waveform.md
+++ b/packages/docs/docs/visualize-audio-waveform.md
@@ -3,71 +3,207 @@ title: visualizeAudioWaveform()
id: visualize-audio-waveform
---
+import { AudioWaveFormExample } from "../components/AudioWaveformExamples.tsx";
+
_Part of the `@remotion/media-utils`_ package of helper functions.
This function takes in `AudioData` (preferrably fetched by the [`useAudioData()`](/docs/use-audio-data) hook) and processes it in a way that makes visualizing the audio waveform that is playing at the current frame easy.
-## Arguments
+```tsx twoslash
+import {
+ createSmoothSvgPath,
+ useAudioData,
+ visualizeAudioWaveform,
+ AudioData,
+} from "@remotion/media-utils";
+import React from "react";
+import { AbsoluteFill, Audio, useCurrentFrame, useVideoConfig } from "remotion";
+import voice from "./voice-short.mp3";
+
+const frame = useCurrentFrame();
+const audioData = useAudioData(voice) as AudioData;
+const { fps } = useVideoConfig();
+
+// ---cut---
+const waveform = visualizeAudioWaveform({
+ fps,
+ frame,
+ audioData,
+ numberOfSamples: 16,
+ windowInSeconds: 1 / fps,
+});
+```
-### `options`
+See [Examples](#examples) below.
+
+:::info
+This function is suitable for visualizing voice. For visualizing music, use [`visualizeAudio()`](/docs/visualize-audio)
+:::
+
+## Arguments
The only argument for this function is an object containing the following values:
-- `audioData`: `AudioData` - an object containing audio data. You can fetch this object using [`useAudioData()`](/docs/use-audio-data) or [`getAudioData()`](/docs/get-audio-data).
+### `audioData`
+
+`AudioData`
+
+An object containing audio data. You can fetch this object using [`useAudioData()`](/docs/use-audio-data) or [`getAudioData()`](/docs/get-audio-data).
+
+### `frame`
+
+`number`
+
+The time of the track that you want to get the audio information for. The `frame` always refers to the position in the audio track - if you have shifted or trimmed the audio in your timeline, the frame returned by `useCurrentFrame` must also be tweaked before you pass it into this function.
+
+### `fps`
+
+`number`
-- `frame`: `number` - the time of the track that you want to get the audio information for. The `frame` always refers to the position in the audio track - if you have shifted or trimmed the audio in your timeline, the frame returned by `useCurrentFrame` must also be tweaked before you pass it into this function.
+The frame rate of the composition. This helps the function understand the meaning of the `frame` input.
-- `fps`: `number` - the frame rate of the composition. This helps the function understand the meaning of the `frame` input.
+### `numberOfSamples`
-- `numberOfSamples`: `number` - must be a power of two, such as `32`, `64`, `128`, etc. This parameter controls the length of the output array. A lower number will simplify the spectrum and is useful if you want to animate elements roughly based on the level of lows, mids and highs. A higher number will give the spectrum in more detail, which is useful for displaying a bar chart or waveform-style visualization of the audio.
+`number`
-- `waveformDuration`: `number` - time in seconds (can be float) which represents the duration for which you want to see the audio waveform data with respect to frame. for example let's say if your video `fps` is 30, and you pass 15 as the `frame` on `visualizeAudioWaveform` and passed 0.25 as `waveformDuration` then output will have audio waveform data from (15/30) - .125 = 0.375 sec to (15/30) +0.125 = 0.625 sec.
+Must be a power of two, such as `32`, `64`, `128`, etc. This parameter controls the length of the output array. A lower number will simplify the spectrum and is useful if you want to animate elements roughly based on the level of lows, mids and highs. A higher number will give the spectrum in more detail, which is useful for displaying a bar chart or waveform-style visualization of the audio.
+
+### `windowInSeconds`
+
+`number`
+
+Time in seconds (can be float) which represents the duration for which you want to see the audio waveform. Example: Your video has an `fps` of 30, and you pass 15 as the `frame` on `visualizeAudioWaveform` and 0.25 as `windowInSeconds` then output will have audio waveform data from (15/30) - .125 = 0.375 sec to (15/30) +0.125 = 0.625 sec.
## Return value
-`number[]` - An array of values describing the amplitude of each frequency range. Each value is between 0 and 1. The array is of length defined by the `numberOfSamples` parameter.
+`number[]`
-## Example
+An array of values describing the amplitude of each frequency range. Each value is between 0 and 1. The array is of length defined by the `numberOfSamples` parameter.
-In this example, we render a bar chart visualizing the audio spectrum of an audio file we imported using [`useAudioData()`](/docs/use-audio-data) and `visualizeAudio()`.
+## Examples
-```tsx twoslash
-import { Audio, useCurrentFrame, useVideoConfig } from "remotion";
-import { useAudioData, visualizeAudioWaveform } from "@remotion/media-utils";
-import music from "./music.mp3";
+### Basic example
-export const MyComponent: React.FC = () => {
+```tsx twoslash
+import {
+ createSmoothSvgPath,
+ useAudioData,
+ visualizeAudioWaveform,
+} from "@remotion/media-utils";
+import React from "react";
+import { AbsoluteFill, Audio, useCurrentFrame, useVideoConfig } from "remotion";
+import voice from "./voice-short.mp3";
+
+const BaseExample: React.FC = () => {
const frame = useCurrentFrame();
+ const audioDataVoice = useAudioData(voice);
const { width, height, fps } = useVideoConfig();
- const audioData = useAudioData(music);
- if (!audioData) {
+ if (!audioDataVoice) {
return null;
}
- const visualization = visualizeAudioWaveform({
+ const waveform = visualizeAudioWaveform({
fps,
frame,
- audioData,
+ audioData: audioDataVoice,
numberOfSamples: 32,
- waveformDuration: 1/fps,
+ windowInSeconds: 1 / fps,
});
+ const p = createSmoothSvgPath(
+ waveform.map((x, i) => {
+ return [
+ (i / (waveform.length - 1)) * width,
+ (x - 0.5) * 300 + height / 2,
+ ];
+ })
+ );
+
return (
- <div>
- <Audio src={music} />
- {visualization.map((v) => {
- return (
- <div
- style={{ width: 1000 * v, height: 15, backgroundColor: "blue" }}
- />
- );
- })}
+ <div style={{ flex: 1 }}>
+ <Audio src={voice} />
+ <AbsoluteFill style={{ justifyContent: "center", alignItems: "center" }}>
+ <svg
+ style={{ backgroundColor: " #0B84F3" }}
+ viewBox={`0 0 ${width} ${height}`}
+ width={width}
+ height={height}
+ >
+ <path stroke="white" fill="none" strokeWidth={10} d={p as string} />
+ </svg>
+ </AbsoluteFill>
</div>
);
};
```
+<AudioWaveFormExample type="base" />
+<br/>
+
+### Sliding effect
+
+By increasing the `windowInSeconds` by tenfold, the audiogram starts moving to the right:
+
+```tsx twoslash {6}
+import {
+ createSmoothSvgPath,
+ useAudioData,
+ visualizeAudioWaveform,
+ AudioData,
+} from "@remotion/media-utils";
+import React from "react";
+import { AbsoluteFill, Audio, useCurrentFrame, useVideoConfig } from "remotion";
+import voice from "./voice-short.mp3";
+
+const frame = useCurrentFrame();
+const audioDataVoice = useAudioData(voice) as AudioData;
+const { fps } = useVideoConfig();
+
+// ---cut---
+const waveform = visualizeAudioWaveform({
+ fps,
+ frame,
+ audioData: audioDataVoice,
+ numberOfSamples: 32,
+ windowInSeconds: 10 / fps,
+});
+```
+
+<AudioWaveFormExample type="moving" />
+<br/>
+
+### Posterizing
+
+By only calculating the waveform every third frame, we make the waveform calmer and generate a cool effect:
+
+```tsx twoslash {3}
+import {
+ createSmoothSvgPath,
+ useAudioData,
+ visualizeAudioWaveform,
+ AudioData,
+} from "@remotion/media-utils";
+import React from "react";
+import { AbsoluteFill, Audio, useCurrentFrame, useVideoConfig } from "remotion";
+import voice from "./voice-short.mp3";
+
+const frame = useCurrentFrame();
+const audioDataVoice = useAudioData(voice) as AudioData;
+const { fps } = useVideoConfig();
+
+// ---cut---
+const waveform = visualizeAudioWaveform({
+ fps,
+ frame: Math.round(frame / 3) * 3,
+ audioData: audioDataVoice,
+ numberOfSamples: 32,
+ windowInSeconds: 10 / fps,
+});
+```
+
+<AudioWaveFormExample type="posterized" />
+
## See also
- [Audio visualization](/docs/audio-visualization)
@@ -75,4 +211,3 @@ export const MyComponent: React.FC = () => {
- [`getAudioData()`](/docs/get-audio-data)
- [`<Audio/>`](/docs/audio)
- [Using audio](/docs/using-audio)
-
diff --git a/packages/example/src/AudioVisualization/index.tsx b/packages/example/src/AudioVisualization/index.tsx
index ba60ff4c4a..07a93d3c9d 100644
--- a/packages/example/src/AudioVisualization/index.tsx
+++ b/packages/example/src/AudioVisualization/index.tsx
@@ -140,7 +140,7 @@ const AudioVisualization: React.FC<{isWaveform: boolean}> = ({isWaveform}) => {
frame,
audioData: audioDataVoice,
numberOfSamples: WAVEFORM_SAMPLES,
- waveformDuration: 1 / fps,
+ windowInSeconds: 1 / fps,
});
const scale =
diff --git a/packages/example/src/voice-visualization/index.tsx b/packages/example/src/voice-visualization/index.tsx
index 11737ca4b3..3160a664cb 100644
--- a/packages/example/src/voice-visualization/index.tsx
+++ b/packages/example/src/voice-visualization/index.tsx
@@ -1,9 +1,9 @@
import {
- AudioData,
+ createSmoothSvgPath,
useAudioData,
visualizeAudioWaveform,
} from '@remotion/media-utils';
-import React, {useEffect, useRef} from 'react';
+import React from 'react';
import {AbsoluteFill, Audio, useCurrentFrame, useVideoConfig} from 'remotion';
import styled from 'styled-components';
import music from '../resources/sound1.mp3';
@@ -22,66 +22,49 @@ const Orb = styled.div`
flex: 1;
`;
-const WAVEFORM_SAMPLES = 16;
-
-const Canvas: React.FC<{waveform: number[]; audioData: AudioData}> = ({
- waveform,
- audioData,
-}) => {
- const {width, height} = useVideoConfig();
- const canvasRef = useRef<HTMLCanvasElement>(null);
- const canvas = canvasRef.current;
- const canvasCtx = canvas?.getContext('2d');
- useEffect(() => {
- if (canvasCtx) {
- canvasCtx.fillStyle = 'rgb(200, 200, 200)';
- canvasCtx.fillRect(0, 0, width, height);
- canvasCtx.lineWidth = 4;
- canvasCtx.strokeStyle = 'rgb(0, 0, 0)';
- canvasCtx.beginPath();
- const sliceWidth = width / (WAVEFORM_SAMPLES - 1);
- let x = 0;
- for (let i = 0; i < waveform.length; i++) {
- const v = waveform[i] / 128.0;
- const y = v * audioData.sampleRate + height / 2;
-
- if (i === 0) {
- canvasCtx.moveTo(x, y);
- } else {
- canvasCtx.lineTo(x, y);
- }
-
- x += sliceWidth;
- }
- canvasCtx.stroke();
- }
- }, [audioData.sampleRate, canvasCtx, height, waveform, width]);
- return <canvas ref={canvasRef} width={width} height={height} />;
-};
-
const VoiceVisualization: React.FC = () => {
const frame = useCurrentFrame();
const {fps} = useVideoConfig();
const audioData = useAudioData(music);
const audioDataVoice = useAudioData(voice);
+ const {width, height} = useVideoConfig();
+
if (!audioData || !audioDataVoice) {
return null;
}
const waveform = visualizeAudioWaveform({
fps,
- frame,
+ frame: Math.round(frame / 3) * 3,
audioData: audioDataVoice,
- numberOfSamples: WAVEFORM_SAMPLES,
- waveformDuration: 1 / fps,
+ numberOfSamples: 16,
+ windowInSeconds: 1 / fps,
});
+ const p = createSmoothSvgPath(
+ waveform.map((p, i) => {
+ return [
+ (i / (waveform.length - 1)) * width * 2 - width / 2,
+ (p - 0.5) * 1000 + width / 2,
+ ];
+ })
+ );
+
+ const filledPath = `${p} L ${width} ${height} L 0 ${height} z`;
+
return (
<div style={{flex: 1}}>
<Audio src={voice} />
<FullSize>
<Orb>
- <Canvas audioData={audioData} waveform={waveform} />
+ <svg
+ style={{backgroundColor: 'white'}}
+ viewBox={`0 0 ${width} ${height}`}
+ width={width}
+ height={height}
+ >
+ <path fill="black" strokeWidth={10} d={filledPath} />
+ </svg>
</Orb>
</FullSize>
</div>
diff --git a/packages/media-utils/src/create-smooth-svg-path.ts b/packages/media-utils/src/create-smooth-svg-path.ts
new file mode 100644
index 0000000000..1414fdd243
--- /dev/null
+++ b/packages/media-utils/src/create-smooth-svg-path.ts
@@ -0,0 +1,30 @@
+export const createSmoothSvgPath = (points: [number, number][]) => {
+ return points.reduce(
+ (acc: string | null, point: [number, number], i: number, a) => {
+ if (i === 0) {
+ return `M ${point[0]},${point[1]}`;
+ }
+
+ const p0 = a[i - 2] || a[i - 1];
+ const x0 = p0[0];
+ const y0 = p0[1];
+ const p1 = a[i - 1];
+ const x1 = p1[0];
+ const y1 = p1[1];
+ const x = point[0];
+ const y = point[1];
+ const cp1x = (2 * x0 + x1) / 3;
+ const cp1y = (2 * y0 + y1) / 3;
+ const cp2x = (x0 + 2 * x1) / 3;
+ const cp2y = (y0 + 2 * y1) / 3;
+ const cp3x = (x0 + 4 * x1 + x) / 6;
+ const cp3y = (y0 + 4 * y1 + y) / 6;
+ if (i === a.length - 1) {
+ return `${acc} C ${cp1x},${cp1y} ${cp2x},${cp2y} ${cp3x},${cp3y} C${x},${y} ${x},${y} ${x},${y}`;
+ }
+
+ return `${acc} C ${cp1x},${cp1y} ${cp2x},${cp2y} ${cp3x},${cp3y}`;
+ },
+ ''
+ );
+};
diff --git a/packages/media-utils/src/index.ts b/packages/media-utils/src/index.ts
index aedb9e4756..539b71f1c5 100644
--- a/packages/media-utils/src/index.ts
+++ b/packages/media-utils/src/index.ts
@@ -7,3 +7,4 @@ export type {AudioData, VideoMetadata as VideoData} from './types';
export {useAudioData} from './use-audio-metadata';
export {visualizeAudio} from './visualize-audio';
export {visualizeAudioWaveform} from './visualize-audio-waveform';
+export {createSmoothSvgPath} from './create-smooth-svg-path';
diff --git a/packages/media-utils/src/visualize-audio-waveform.ts b/packages/media-utils/src/visualize-audio-waveform.ts
index 890995e1de..ea5007f420 100644
--- a/packages/media-utils/src/visualize-audio-waveform.ts
+++ b/packages/media-utils/src/visualize-audio-waveform.ts
@@ -7,7 +7,7 @@ type FnParameters = {
audioData: AudioData;
frame: number;
fps: number;
- waveformDuration: number;
+ windowInSeconds: number;
numberOfSamples: number;
};
@@ -16,14 +16,14 @@ const visualizeAudioWaveformFrame = ({
frame,
fps,
numberOfSamples,
- waveformDuration,
+ windowInSeconds,
}: FnParameters) => {
- if (waveformDuration * audioData.sampleRate < numberOfSamples) {
+ if (windowInSeconds * audioData.sampleRate < numberOfSamples) {
throw new TypeError(
- waveformDuration +
+ windowInSeconds +
's audiodata does not have ' +
numberOfSamples +
- ' bars. Increase waveformDuration or decrease numberOfSamples'
+ ' bars. Increase windowInSeconds or decrease numberOfSamples'
);
}
@@ -33,18 +33,22 @@ const visualizeAudioWaveformFrame = ({
return cache[cacheKey];
}
- const startTimeInSeconds =
- frame / fps < waveformDuration
- ? 0
- : frame / fps + waveformDuration / 2 >= audioData.durationInSeconds
- ? audioData.durationInSeconds - waveformDuration
- : frame / fps - waveformDuration / 2;
+ const time = frame / fps;
+
+ const max = audioData.durationInSeconds - windowInSeconds / 2;
+ const min = windowInSeconds / 2;
+
+ const startTimeInSeconds = Math.min(
+ max,
+ Math.max(min, time - windowInSeconds / 2)
+ );
+
return getWaveformPortion({
audioData,
startTimeInSeconds,
- durationInSeconds: waveformDuration,
+ durationInSeconds: windowInSeconds,
numberOfSamples,
- normalize: false,
+ normalize: true,
});
};