1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
|
"use client";
import { useCallback, useEffect, useRef } from "react";
import { useResizeObserver } from "@/hooks/use-resize-observer";
import { computeGlobalMaxRms, extractRmsRange } from "@/lib/media/audio";
import { findScrollParent } from "@/utils/browser";
import { cn } from "@/utils/ui";
const BAR_WIDTH = 2;
const BAR_GAP = 1;
const BAR_STEP = BAR_WIDTH + BAR_GAP;
export const WAVEFORM_GAIN_SAMPLE_COUNT = 200;
function sampleGain({
samples,
startFraction,
endFraction,
barIndex,
barCount,
}: {
samples: number[];
startFraction: number;
endFraction: number;
barIndex: number;
barCount: number;
}): number {
if (samples.length === 0) return 1;
const progress =
startFraction +
((barIndex + 0.5) / barCount) * (endFraction - startFraction);
const rawIndex = Math.max(0, Math.min(1, progress)) * (samples.length - 1);
const lo = Math.floor(rawIndex);
const hi = Math.min(samples.length - 1, lo + 1);
return samples[lo] + (samples[hi] - samples[lo]) * (rawIndex - lo);
}
interface AudioWaveformProps {
audioUrl?: string;
audioBuffer?: AudioBuffer;
gainSamples?: number[];
color?: string;
className?: string;
}
export function AudioWaveform({
audioUrl,
audioBuffer,
gainSamples,
color = "rgba(255, 255, 255, 0.7)",
className = "",
}: AudioWaveformProps) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const bufferRef = useRef<AudioBuffer | null>(null);
const globalMaxRef = useRef<number>(1);
const gainSamplesRef = useRef<number[] | undefined>(gainSamples);
const scrollParentRef = useRef<HTMLElement | null>(null);
const heightRef = useRef<number>(0);
const drawVisible = useCallback(() => {
const container = containerRef.current;
const canvas = canvasRef.current;
const buffer = bufferRef.current;
const height = heightRef.current;
if (!container || !canvas || !buffer || height <= 0) return;
const elementWidth = container.offsetWidth;
if (elementWidth <= 0) return;
const containerRect = container.getBoundingClientRect();
const scrollParent = scrollParentRef.current;
let clipLeft: number;
let clipRight: number;
if (scrollParent) {
const parentRect = scrollParent.getBoundingClientRect();
clipLeft = Math.max(0, parentRect.left - containerRect.left);
clipRight = Math.min(elementWidth, parentRect.right - containerRect.left);
} else {
clipLeft = Math.max(0, -containerRect.left);
clipRight = Math.min(
elementWidth,
window.innerWidth - containerRect.left,
);
}
const visibleWidth = clipRight - clipLeft;
if (visibleWidth <= 0) return;
const dpr = window.devicePixelRatio || 1;
const canvasW = Math.round(visibleWidth * dpr);
const canvasH = Math.round(height * dpr);
if (canvasW <= 0 || canvasH <= 0) return;
canvas.width = canvasW;
canvas.height = canvasH;
canvas.style.width = `${visibleWidth}px`;
canvas.style.height = `${height}px`;
canvas.style.left = `${clipLeft}px`;
const barCount = Math.max(1, Math.floor(visibleWidth / BAR_STEP));
const startFraction = clipLeft / elementWidth;
const endFraction = clipRight / elementWidth;
const startSample = Math.floor(startFraction * buffer.length);
const endSample = Math.min(
buffer.length,
Math.ceil(endFraction * buffer.length),
);
const peaks = extractRmsRange({
buffer,
count: barCount,
startSample,
endSample,
globalMax: globalMaxRef.current,
});
const ctx = canvas.getContext("2d");
if (!ctx) return;
ctx.clearRect(0, 0, canvasW, canvasH);
ctx.scale(dpr, dpr);
ctx.fillStyle = color;
const maxBarHeight = height * 0.7;
const samples = gainSamplesRef.current;
for (let i = 0; i < barCount; i++) {
const gain =
samples != null
? sampleGain({
samples,
startFraction,
endFraction,
barIndex: i,
barCount,
})
: 1;
const scaledPeak = Math.min(1, Math.max(0, peaks[i] * gain));
const scaled = Math.log1p(scaledPeak) / Math.log1p(1);
const barH = Math.max(1, scaled * maxBarHeight);
ctx.fillRect(i * BAR_STEP, height - barH, BAR_WIDTH, barH);
}
}, [color]);
useEffect(() => {
gainSamplesRef.current = gainSamples;
drawVisible();
}, [gainSamples, drawVisible]);
useEffect(() => {
let isCancelled = false;
async function load() {
let buffer = audioBuffer ?? null;
if (!buffer && audioUrl) {
try {
const resp = await fetch(audioUrl);
const arrayBuffer = await resp.arrayBuffer();
const actx = new AudioContext();
buffer = await actx.decodeAudioData(arrayBuffer);
actx.close();
} catch {
return;
}
}
if (!buffer || isCancelled) return;
bufferRef.current = buffer;
globalMaxRef.current = computeGlobalMaxRms({ buffer });
drawVisible();
}
load();
return () => {
isCancelled = true;
};
}, [audioUrl, audioBuffer, drawVisible]);
useEffect(() => {
const container = containerRef.current;
if (!container) return;
scrollParentRef.current = findScrollParent({ element: container });
const scrollParent = scrollParentRef.current;
if (!scrollParent) return;
scrollParent.addEventListener("scroll", drawVisible, { passive: true });
return () => scrollParent.removeEventListener("scroll", drawVisible);
}, [drawVisible]);
const onResize = useCallback(
(entry: ResizeObserverEntry) => {
heightRef.current = entry.contentRect.height;
drawVisible();
},
[drawVisible],
);
useResizeObserver({ ref: containerRef, onResize });
return (
<div ref={containerRef} className={cn("relative size-full", className)}>
<canvas ref={canvasRef} className="absolute bottom-0" />
</div>
);
}
|