A live-waveform component from ElevenLabs UI.
From ElevenLabs UIMITSource
1"use client"
2
3import { useEffect, useRef, type HTMLAttributes } from "react"
4
5import { cn } from "@/lib/utils"
6
7export type LiveWaveformProps = HTMLAttributes<HTMLDivElement> & {
8 active?: boolean
9 processing?: boolean
10 deviceId?: string
11 barWidth?: number
12 barHeight?: number
13 barGap?: number
14 barRadius?: number
15 barColor?: string
16 fadeEdges?: boolean
17 fadeWidth?: number
18 height?: string | number
19 sensitivity?: number
20 smoothingTimeConstant?: number
21 fftSize?: number
22 historySize?: number
23 updateRate?: number
24 mode?: "scrolling" | "static"
25 onError?: (error: Error) => void
26 onStreamReady?: (stream: MediaStream) => void
27 onStreamEnd?: () => void
28}
29
30export const LiveWaveform = ({
31 active = false,
32 processing = false,
33 deviceId,
34 barWidth = 3,
35 barGap = 1,
36 barRadius = 1.5,
37 barColor,
38 fadeEdges = true,
39 fadeWidth = 24,
40 barHeight: baseBarHeight = 4,
41 height = 64,
42 sensitivity = 1,
43 smoothingTimeConstant = 0.8,
44 fftSize = 256,
45 historySize = 60,
46 updateRate = 30,
47 mode = "static",
48 onError,
49 onStreamReady,
50 onStreamEnd,
51 className,
52 ...props
53}: LiveWaveformProps) => {
54 const canvasRef = useRef<HTMLCanvasElement>(null)
55 const containerRef = useRef<HTMLDivElement>(null)
56 const historyRef = useRef<number[]>([])
57 const analyserRef = useRef<AnalyserNode | null>(null)
58 const audioContextRef = useRef<AudioContext | null>(null)
59 const streamRef = useRef<MediaStream | null>(null)
60 const animationRef = useRef<number>(0)
61 const lastUpdateRef = useRef<number>(0)
62 const processingAnimationRef = useRef<number | null>(null)
63 const lastActiveDataRef = useRef<number[]>([])
64 const transitionProgressRef = useRef(0)
65 const staticBarsRef = useRef<number[]>([])
66 const needsRedrawRef = useRef(true)
67 const gradientCacheRef = useRef<CanvasGradient | null>(null)
68 const lastWidthRef = useRef(0)
69
70 const heightStyle = typeof height === "number" ? `${height}px` : height
71
72 // Handle canvas resizing
73 useEffect(() => {
74 const canvas = canvasRef.current
75 const container = containerRef.current
76 if (!canvas || !container) return
77
78 const resizeObserver = new ResizeObserver(() => {
79 const rect = container.getBoundingClientRect()
80 const dpr = window.devicePixelRatio || 1
81
82 canvas.width = rect.width * dpr
83 canvas.height = rect.height * dpr
84 canvas.style.width = `${rect.width}px`
85 canvas.style.height = `${rect.height}px`
86
87 const ctx = canvas.getContext("2d")
88 if (ctx) {
89 ctx.scale(dpr, dpr)
90 }
91
92 gradientCacheRef.current = null
93 lastWidthRef.current = rect.width
94 needsRedrawRef.current = true
95 })
96
97 resizeObserver.observe(container)
98 return () => resizeObserver.disconnect()
99 }, [])
100
101 useEffect(() => {
102 if (processing && !active) {
103 let time = 0
104 transitionProgressRef.current = 0
105
106 const animateProcessing = () => {
107 time += 0.03
108 transitionProgressRef.current = Math.min(
109 1,
110 transitionProgressRef.current + 0.02
111 )
112
113 const processingData = []
114 const barCount = Math.floor(
115 (containerRef.current?.getBoundingClientRect().width || 200) /
116 (barWidth + barGap)
117 )
118
119 if (mode === "static") {
120 const halfCount = Math.floor(barCount / 2)
121
122 for (let i = 0; i < barCount; i++) {
123 const normalizedPosition = (i - halfCount) / halfCount
124 const centerWeight = 1 - Math.abs(normalizedPosition) * 0.4
125
126 const wave1 = Math.sin(time * 1.5 + normalizedPosition * 3) * 0.25
127 const wave2 = Math.sin(time * 0.8 - normalizedPosition * 2) * 0.2
128 const wave3 = Math.cos(time * 2 + normalizedPosition) * 0.15
129 const combinedWave = wave1 + wave2 + wave3
130 const processingValue = (0.2 + combinedWave) * centerWeight
131
132 let finalValue = processingValue
133 if (
134 lastActiveDataRef.current.length > 0 &&
135 transitionProgressRef.current < 1
136 ) {
137 const lastDataIndex = Math.min(
138 i,
139 lastActiveDataRef.current.length - 1
140 )
141 const lastValue = lastActiveDataRef.current[lastDataIndex] || 0
142 finalValue =
143 lastValue * (1 - transitionProgressRef.current) +
144 processingValue * transitionProgressRef.current
145 }
146
147 processingData.push(Math.max(0.05, Math.min(1, finalValue)))
148 }
149 } else {
150 for (let i = 0; i < barCount; i++) {
151 const normalizedPosition = (i - barCount / 2) / (barCount / 2)
152 const centerWeight = 1 - Math.abs(normalizedPosition) * 0.4
153
154 const wave1 = Math.sin(time * 1.5 + i * 0.15) * 0.25
155 const wave2 = Math.sin(time * 0.8 - i * 0.1) * 0.2
156 const wave3 = Math.cos(time * 2 + i * 0.05) * 0.15
157 const combinedWave = wave1 + wave2 + wave3
158 const processingValue = (0.2 + combinedWave) * centerWeight
159
160 let finalValue = processingValue
161 if (
162 lastActiveDataRef.current.length > 0 &&
163 transitionProgressRef.current < 1
164 ) {
165 const lastDataIndex = Math.floor(
166 (i / barCount) * lastActiveDataRef.current.length
167 )
168 const lastValue = lastActiveDataRef.current[lastDataIndex] || 0
169 finalValue =
170 lastValue * (1 - transitionProgressRef.current) +
171 processingValue * transitionProgressRef.current
172 }
173
174 processingData.push(Math.max(0.05, Math.min(1, finalValue)))
175 }
176 }
177
178 if (mode === "static") {
179 staticBarsRef.current = processingData
180 } else {
181 historyRef.current = processingData
182 }
183
184 needsRedrawRef.current = true
185 processingAnimationRef.current =
186 requestAnimationFrame(animateProcessing)
187 }
188
189 animateProcessing()
190
191 return () => {
192 if (processingAnimationRef.current) {
193 cancelAnimationFrame(processingAnimationRef.current)
194 }
195 }
196 } else if (!active && !processing) {
197 const hasData =
198 mode === "static"
199 ? staticBarsRef.current.length > 0
200 : historyRef.current.length > 0
201
202 if (hasData) {
203 let fadeProgress = 0
204 const fadeToIdle = () => {
205 fadeProgress += 0.03
206 if (fadeProgress < 1) {
207 if (mode === "static") {
208 staticBarsRef.current = staticBarsRef.current.map(
209 (value) => value * (1 - fadeProgress)
210 )
211 } else {
212 historyRef.current = historyRef.current.map(
213 (value) => value * (1 - fadeProgress)
214 )
215 }
216 needsRedrawRef.current = true
217 requestAnimationFrame(fadeToIdle)
218 } else {
219 if (mode === "static") {
220 staticBarsRef.current = []
221 } else {
222 historyRef.current = []
223 }
224 }
225 }
226 fadeToIdle()
227 }
228 }
229 }, [processing, active, barWidth, barGap, mode])
230
231 // Handle microphone setup and teardown
232 useEffect(() => {
233 if (!active) {
234 if (streamRef.current) {
235 streamRef.current.getTracks().forEach((track) => track.stop())
236 streamRef.current = null
237 onStreamEnd?.()
238 }
239 if (
240 audioContextRef.current &&
241 audioContextRef.current.state !== "closed"
242 ) {
243 audioContextRef.current.close()
244 audioContextRef.current = null
245 }
246 if (animationRef.current) {
247 cancelAnimationFrame(animationRef.current)
248 animationRef.current = 0
249 }
250 return
251 }
252
253 const setupMicrophone = async () => {
254 try {
255 const stream = await navigator.mediaDevices.getUserMedia({
256 audio: deviceId
257 ? {
258 deviceId: { exact: deviceId },
259 echoCancellation: true,
260 noiseSuppression: true,
261 autoGainControl: true,
262 }
263 : {
264 echoCancellation: true,
265 noiseSuppression: true,
266 autoGainControl: true,
267 },
268 })
269 streamRef.current = stream
270 onStreamReady?.(stream)
271
272 const AudioContextConstructor =
273 window.AudioContext ||
274 (window as unknown as { webkitAudioContext: typeof AudioContext })
275 .webkitAudioContext
276 const audioContext = new AudioContextConstructor()
277 const analyser = audioContext.createAnalyser()
278 analyser.fftSize = fftSize
279 analyser.smoothingTimeConstant = smoothingTimeConstant
280
281 const source = audioContext.createMediaStreamSource(stream)
282 source.connect(analyser)
283
284 audioContextRef.current = audioContext
285 analyserRef.current = analyser
286
287 // Clear history when starting
288 historyRef.current = []
289 } catch (error) {
290 onError?.(error as Error)
291 }
292 }
293
294 setupMicrophone()
295
296 return () => {
297 if (streamRef.current) {
298 streamRef.current.getTracks().forEach((track) => track.stop())
299 streamRef.current = null
300 onStreamEnd?.()
301 }
302 if (
303 audioContextRef.current &&
304 audioContextRef.current.state !== "closed"
305 ) {
306 audioContextRef.current.close()
307 audioContextRef.current = null
308 }
309 if (animationRef.current) {
310 cancelAnimationFrame(animationRef.current)
311 animationRef.current = 0
312 }
313 }
314 }, [
315 active,
316 deviceId,
317 fftSize,
318 smoothingTimeConstant,
319 onError,
320 onStreamReady,
321 onStreamEnd,
322 ])
323
324 // Animation loop
325 useEffect(() => {
326 const canvas = canvasRef.current
327 if (!canvas) return
328
329 const ctx = canvas.getContext("2d")
330 if (!ctx) return
331
332 let rafId: number
333
334 const animate = (currentTime: number) => {
335 // Render waveform
336 const rect = canvas.getBoundingClientRect()
337
338 // Update audio data if active
339 if (active && currentTime - lastUpdateRef.current > updateRate) {
340 lastUpdateRef.current = currentTime
341
342 if (analyserRef.current) {
343 const dataArray = new Uint8Array(
344 analyserRef.current.frequencyBinCount
345 )
346 analyserRef.current.getByteFrequencyData(dataArray)
347
348 if (mode === "static") {
349 // For static mode, update bars in place
350 const startFreq = Math.floor(dataArray.length * 0.05)
351 const endFreq = Math.floor(dataArray.length * 0.4)
352 const relevantData = dataArray.slice(startFreq, endFreq)
353
354 const barCount = Math.floor(rect.width / (barWidth + barGap))
355 const halfCount = Math.floor(barCount / 2)
356 const newBars: number[] = []
357
358 // Mirror the data for symmetric display
359 for (let i = halfCount - 1; i >= 0; i--) {
360 const dataIndex = Math.floor(
361 (i / halfCount) * relevantData.length
362 )
363 const value = Math.min(
364 1,
365 (relevantData[dataIndex] / 255) * sensitivity
366 )
367 newBars.push(Math.max(0.05, value))
368 }
369
370 for (let i = 0; i < halfCount; i++) {
371 const dataIndex = Math.floor(
372 (i / halfCount) * relevantData.length
373 )
374 const value = Math.min(
375 1,
376 (relevantData[dataIndex] / 255) * sensitivity
377 )
378 newBars.push(Math.max(0.05, value))
379 }
380
381 staticBarsRef.current = newBars
382 lastActiveDataRef.current = newBars
383 } else {
384 // Scrolling mode - original behavior
385 let sum = 0
386 const startFreq = Math.floor(dataArray.length * 0.05)
387 const endFreq = Math.floor(dataArray.length * 0.4)
388 const relevantData = dataArray.slice(startFreq, endFreq)
389
390 for (let i = 0; i < relevantData.length; i++) {
391 sum += relevantData[i]
392 }
393 const average = (sum / relevantData.length / 255) * sensitivity
394
395 // Add to history
396 historyRef.current.push(Math.min(1, Math.max(0.05, average)))
397 lastActiveDataRef.current = [...historyRef.current]
398
399 // Maintain history size
400 if (historyRef.current.length > historySize) {
401 historyRef.current.shift()
402 }
403 }
404 needsRedrawRef.current = true
405 }
406 }
407
408 // Only redraw if needed
409 if (!needsRedrawRef.current && !active) {
410 rafId = requestAnimationFrame(animate)
411 return
412 }
413
414 needsRedrawRef.current = active
415 ctx.clearRect(0, 0, rect.width, rect.height)
416
417 const computedBarColor =
418 barColor ||
419 (() => {
420 const style = getComputedStyle(canvas)
421 // Try to get the computed color value directly
422 const color = style.color
423 return color || "#000"
424 })()
425
426 const step = barWidth + barGap
427 const barCount = Math.floor(rect.width / step)
428 const centerY = rect.height / 2
429
430 // Draw bars based on mode
431 if (mode === "static") {
432 // Static mode - bars in fixed positions
433 const dataToRender = processing
434 ? staticBarsRef.current
435 : active
436 ? staticBarsRef.current
437 : staticBarsRef.current.length > 0
438 ? staticBarsRef.current
439 : []
440
441 for (let i = 0; i < barCount && i < dataToRender.length; i++) {
442 const value = dataToRender[i] || 0.1
443 const x = i * step
444 const barHeight = Math.max(baseBarHeight, value * rect.height * 0.8)
445 const y = centerY - barHeight / 2
446
447 ctx.fillStyle = computedBarColor
448 ctx.globalAlpha = 0.4 + value * 0.6
449
450 if (barRadius > 0) {
451 ctx.beginPath()
452 ctx.roundRect(x, y, barWidth, barHeight, barRadius)
453 ctx.fill()
454 } else {
455 ctx.fillRect(x, y, barWidth, barHeight)
456 }
457 }
458 } else {
459 // Scrolling mode - original behavior
460 for (let i = 0; i < barCount && i < historyRef.current.length; i++) {
461 const dataIndex = historyRef.current.length - 1 - i
462 const value = historyRef.current[dataIndex] || 0.1
463 const x = rect.width - (i + 1) * step
464 const barHeight = Math.max(baseBarHeight, value * rect.height * 0.8)
465 const y = centerY - barHeight / 2
466
467 ctx.fillStyle = computedBarColor
468 ctx.globalAlpha = 0.4 + value * 0.6
469
470 if (barRadius > 0) {
471 ctx.beginPath()
472 ctx.roundRect(x, y, barWidth, barHeight, barRadius)
473 ctx.fill()
474 } else {
475 ctx.fillRect(x, y, barWidth, barHeight)
476 }
477 }
478 }
479
480 // Apply edge fading
481 if (fadeEdges && fadeWidth > 0 && rect.width > 0) {
482 // Cache gradient if width hasn't changed
483 if (!gradientCacheRef.current || lastWidthRef.current !== rect.width) {
484 const gradient = ctx.createLinearGradient(0, 0, rect.width, 0)
485 const fadePercent = Math.min(0.3, fadeWidth / rect.width)
486
487 // destination-out: removes destination where source alpha is high
488 // We want: fade edges out, keep center solid
489 // Left edge: start opaque (1) = remove, fade to transparent (0) = keep
490 gradient.addColorStop(0, "rgba(255,255,255,1)")
491 gradient.addColorStop(fadePercent, "rgba(255,255,255,0)")
492 // Center stays transparent = keep everything
493 gradient.addColorStop(1 - fadePercent, "rgba(255,255,255,0)")
494 // Right edge: fade from transparent (0) = keep to opaque (1) = remove
495 gradient.addColorStop(1, "rgba(255,255,255,1)")
496
497 gradientCacheRef.current = gradient
498 lastWidthRef.current = rect.width
499 }
500
501 ctx.globalCompositeOperation = "destination-out"
502 ctx.fillStyle = gradientCacheRef.current
503 ctx.fillRect(0, 0, rect.width, rect.height)
504 ctx.globalCompositeOperation = "source-over"
505 }
506
507 ctx.globalAlpha = 1
508
509 rafId = requestAnimationFrame(animate)
510 }
511
512 rafId = requestAnimationFrame(animate)
513
514 return () => {
515 if (rafId) {
516 cancelAnimationFrame(rafId)
517 }
518 }
519 }, [
520 active,
521 processing,
522 sensitivity,
523 updateRate,
524 historySize,
525 barWidth,
526 baseBarHeight,
527 barGap,
528 barRadius,
529 barColor,
530 fadeEdges,
531 fadeWidth,
532 mode,
533 ])
534
535 return (
536 <div
537 className={cn("relative h-full w-full", className)}
538 ref={containerRef}
539 style={{ height: heightStyle }}
540 aria-label={
541 active
542 ? "Live audio waveform"
543 : processing
544 ? "Processing audio"
545 : "Audio waveform idle"
546 }
547 role="img"
548 {...props}
549 >
550 {!active && !processing && (
551 <div className="border-muted-foreground/20 absolute top-1/2 right-0 left-0 -translate-y-1/2 border-t-2 border-dotted" />
552 )}
553 <canvas
554 className="block h-full w-full"
555 ref={canvasRef}
556 aria-hidden="true"
557 />
558 </div>
559 )
560}
561