A bar-visualizer component from ElevenLabs UI.
From ElevenLabs UIMITSource
1"use client"
2
3import * as React from "react"
4import { useEffect, useMemo, useRef, useState } from "react"
5
6import { cn } from "@/lib/utils"
7
8export interface AudioAnalyserOptions {
9 fftSize?: number
10 smoothingTimeConstant?: number
11 minDecibels?: number
12 maxDecibels?: number
13}
14
15function createAudioAnalyser(
16 mediaStream: MediaStream,
17 options: AudioAnalyserOptions = {}
18) {
19 const audioContext = new (window.AudioContext ||
20 (window as unknown as { webkitAudioContext: typeof AudioContext })
21 .webkitAudioContext)()
22 const source = audioContext.createMediaStreamSource(mediaStream)
23 const analyser = audioContext.createAnalyser()
24
25 if (options.fftSize) analyser.fftSize = options.fftSize
26 if (options.smoothingTimeConstant !== undefined) {
27 analyser.smoothingTimeConstant = options.smoothingTimeConstant
28 }
29 if (options.minDecibels !== undefined)
30 analyser.minDecibels = options.minDecibels
31 if (options.maxDecibels !== undefined)
32 analyser.maxDecibels = options.maxDecibels
33
34 source.connect(analyser)
35
36 const cleanup = () => {
37 source.disconnect()
38 audioContext.close()
39 }
40
41 return { analyser, audioContext, cleanup }
42}
43
44/**
45 * Hook for tracking the volume of an audio stream using the Web Audio API.
46 * @param mediaStream - The MediaStream to analyze
47 * @param options - Audio analyser options
48 * @returns The current volume level (0-1)
49 */
50export function useAudioVolume(
51 mediaStream?: MediaStream | null,
52 options: AudioAnalyserOptions = { fftSize: 32, smoothingTimeConstant: 0 }
53) {
54 const [volume, setVolume] = useState(0)
55 const volumeRef = useRef(0)
56 const frameId = useRef<number | undefined>(undefined)
57
58 // Memoize options to prevent unnecessary re-renders
59 const memoizedOptions = useMemo(
60 () => options,
61 [
62 options.fftSize,
63 options.smoothingTimeConstant,
64 options.minDecibels,
65 options.maxDecibels,
66 ]
67 )
68
69 useEffect(() => {
70 if (!mediaStream) {
71 setVolume(0)
72 volumeRef.current = 0
73 return
74 }
75
76 const { analyser, cleanup } = createAudioAnalyser(
77 mediaStream,
78 memoizedOptions
79 )
80
81 const bufferLength = analyser.frequencyBinCount
82 const dataArray = new Uint8Array(bufferLength)
83 let lastUpdate = 0
84 const updateInterval = 1000 / 30 // 30 FPS
85
86 const updateVolume = (timestamp: number) => {
87 if (timestamp - lastUpdate >= updateInterval) {
88 analyser.getByteFrequencyData(dataArray)
89 let sum = 0
90 for (let i = 0; i < dataArray.length; i++) {
91 const a = dataArray[i]
92 sum += a * a
93 }
94 const newVolume = Math.sqrt(sum / dataArray.length) / 255
95
96 // Only update state if volume changed significantly
97 if (Math.abs(newVolume - volumeRef.current) > 0.01) {
98 volumeRef.current = newVolume
99 setVolume(newVolume)
100 }
101 lastUpdate = timestamp
102 }
103 frameId.current = requestAnimationFrame(updateVolume)
104 }
105
106 frameId.current = requestAnimationFrame(updateVolume)
107
108 return () => {
109 cleanup()
110 if (frameId.current) {
111 cancelAnimationFrame(frameId.current)
112 }
113 }
114 }, [mediaStream, memoizedOptions])
115
116 return volume
117}
118
119export interface MultiBandVolumeOptions {
120 bands?: number
121 loPass?: number // Low frequency cutoff
122 hiPass?: number // High frequency cutoff
123 updateInterval?: number // Update interval in ms
124 analyserOptions?: AudioAnalyserOptions
125}
126
127const multibandDefaults: MultiBandVolumeOptions = {
128 bands: 5,
129 loPass: 100,
130 hiPass: 600,
131 updateInterval: 32,
132 analyserOptions: { fftSize: 2048 },
133}
134
135// Memoized normalization function to avoid recreating on each render
136const normalizeDb = (value: number) => {
137 if (value === -Infinity) return 0
138 const minDb = -100
139 const maxDb = -10
140 const db = 1 - (Math.max(minDb, Math.min(maxDb, value)) * -1) / 100
141 return Math.sqrt(db)
142}
143
144/**
145 * Hook for tracking volume across multiple frequency bands
146 * @param mediaStream - The MediaStream to analyze
147 * @param options - Multiband options
148 * @returns Array of volume levels for each frequency band
149 */
150export function useMultibandVolume(
151 mediaStream?: MediaStream | null,
152 options: MultiBandVolumeOptions = {}
153) {
154 const opts = useMemo(
155 () => ({ ...multibandDefaults, ...options }),
156 [
157 options.bands,
158 options.loPass,
159 options.hiPass,
160 options.updateInterval,
161 options.analyserOptions?.fftSize,
162 options.analyserOptions?.smoothingTimeConstant,
163 options.analyserOptions?.minDecibels,
164 options.analyserOptions?.maxDecibels,
165 ]
166 )
167
168 const [frequencyBands, setFrequencyBands] = useState<number[]>(() =>
169 new Array(opts.bands).fill(0)
170 )
171 const bandsRef = useRef<number[]>(new Array(opts.bands).fill(0))
172 const frameId = useRef<number | undefined>(undefined)
173
174 useEffect(() => {
175 if (!mediaStream) {
176 const emptyBands = new Array(opts.bands).fill(0)
177 setFrequencyBands(emptyBands)
178 bandsRef.current = emptyBands
179 return
180 }
181
182 const { analyser, cleanup } = createAudioAnalyser(
183 mediaStream,
184 opts.analyserOptions
185 )
186
187 const bufferLength = analyser.frequencyBinCount
188 const dataArray = new Float32Array(bufferLength)
189 const sliceStart = opts.loPass!
190 const sliceEnd = opts.hiPass!
191 const sliceLength = sliceEnd - sliceStart
192 const chunkSize = Math.ceil(sliceLength / opts.bands!)
193
194 let lastUpdate = 0
195 const updateInterval = opts.updateInterval!
196
197 const updateVolume = (timestamp: number) => {
198 if (timestamp - lastUpdate >= updateInterval) {
199 analyser.getFloatFrequencyData(dataArray)
200
201 // Process directly without creating intermediate arrays
202 const chunks = new Array(opts.bands!)
203
204 for (let i = 0; i < opts.bands!; i++) {
205 let sum = 0
206 let count = 0
207 const startIdx = sliceStart + i * chunkSize
208 const endIdx = Math.min(sliceStart + (i + 1) * chunkSize, sliceEnd)
209
210 for (let j = startIdx; j < endIdx; j++) {
211 sum += normalizeDb(dataArray[j])
212 count++
213 }
214
215 chunks[i] = count > 0 ? sum / count : 0
216 }
217
218 // Only update state if bands changed significantly
219 let hasChanged = false
220 for (let i = 0; i < chunks.length; i++) {
221 if (Math.abs(chunks[i] - bandsRef.current[i]) > 0.01) {
222 hasChanged = true
223 break
224 }
225 }
226
227 if (hasChanged) {
228 bandsRef.current = chunks
229 setFrequencyBands(chunks)
230 }
231
232 lastUpdate = timestamp
233 }
234
235 frameId.current = requestAnimationFrame(updateVolume)
236 }
237
238 frameId.current = requestAnimationFrame(updateVolume)
239
240 return () => {
241 cleanup()
242 if (frameId.current) {
243 cancelAnimationFrame(frameId.current)
244 }
245 }
246 }, [mediaStream, opts])
247
248 return frequencyBands
249}
250
251type AnimationState =
252 | "connecting"
253 | "initializing"
254 | "listening"
255 | "speaking"
256 | "thinking"
257 | undefined
258
259export const useBarAnimator = (
260 state: AnimationState,
261 columns: number,
262 interval: number
263): number[] => {
264 const indexRef = useRef(0)
265 const [currentFrame, setCurrentFrame] = useState<number[]>([])
266 const animationFrameId = useRef<number | null>(null)
267
268 // Memoize sequence generation
269 const sequence = useMemo(() => {
270 if (state === "thinking" || state === "listening") {
271 return generateListeningSequenceBar(columns)
272 } else if (state === "connecting" || state === "initializing") {
273 return generateConnectingSequenceBar(columns)
274 } else if (state === undefined || state === "speaking") {
275 return [new Array(columns).fill(0).map((_, idx) => idx)]
276 } else {
277 return [[]]
278 }
279 }, [state, columns])
280
281 useEffect(() => {
282 indexRef.current = 0
283 setCurrentFrame(sequence[0] || [])
284 }, [sequence])
285
286 useEffect(() => {
287 let startTime = performance.now()
288
289 const animate = (time: DOMHighResTimeStamp) => {
290 const timeElapsed = time - startTime
291
292 if (timeElapsed >= interval) {
293 indexRef.current = (indexRef.current + 1) % sequence.length
294 setCurrentFrame(sequence[indexRef.current] || [])
295 startTime = time
296 }
297
298 animationFrameId.current = requestAnimationFrame(animate)
299 }
300
301 animationFrameId.current = requestAnimationFrame(animate)
302
303 return () => {
304 if (animationFrameId.current !== null) {
305 cancelAnimationFrame(animationFrameId.current)
306 }
307 }
308 }, [interval, sequence])
309
310 return currentFrame
311}
312
313// Memoize sequence generators
314const generateConnectingSequenceBar = (columns: number): number[][] => {
315 const seq = []
316 for (let x = 0; x < columns; x++) {
317 seq.push([x, columns - 1 - x])
318 }
319 return seq
320}
321
322const generateListeningSequenceBar = (columns: number): number[][] => {
323 const center = Math.floor(columns / 2)
324 const noIndex = -1
325 return [[center], [noIndex]]
326}
327
328export type AgentState =
329 | "connecting"
330 | "initializing"
331 | "listening"
332 | "speaking"
333 | "thinking"
334
335export interface BarVisualizerProps
336 extends React.HTMLAttributes<HTMLDivElement> {
337 /** Voice assistant state */
338 state?: AgentState
339 /** Number of bars to display */
340 barCount?: number
341 /** Audio source */
342 mediaStream?: MediaStream | null
343 /** Min/max height as percentage */
344 minHeight?: number
345 maxHeight?: number
346 /** Enable demo mode with fake audio data */
347 demo?: boolean
348 /** Align bars from center instead of bottom */
349 centerAlign?: boolean
350}
351
352const BarVisualizerComponent = React.forwardRef<
353 HTMLDivElement,
354 BarVisualizerProps
355>(
356 (
357 {
358 state,
359 barCount = 15,
360 mediaStream,
361 minHeight = 20,
362 maxHeight = 100,
363 demo = false,
364 centerAlign = false,
365 className,
366 style,
367 ...props
368 },
369 ref
370 ) => {
371 // Audio processing
372 const realVolumeBands = useMultibandVolume(mediaStream, {
373 bands: barCount,
374 loPass: 100,
375 hiPass: 200,
376 })
377
378 // Generate fake volume data for demo mode using refs to avoid state updates
379 const fakeVolumeBandsRef = useRef<number[]>(new Array(barCount).fill(0.2))
380 const [fakeVolumeBands, setFakeVolumeBands] = useState<number[]>(() =>
381 new Array(barCount).fill(0.2)
382 )
383 const fakeAnimationRef = useRef<number | undefined>(undefined)
384
385 // Animate fake volume bands for speaking and listening states
386 useEffect(() => {
387 if (!demo) return
388
389 if (state !== "speaking" && state !== "listening") {
390 const bands = new Array(barCount).fill(0.2)
391 fakeVolumeBandsRef.current = bands
392 setFakeVolumeBands(bands)
393 return
394 }
395
396 let lastUpdate = 0
397 const updateInterval = 50
398 const startTime = Date.now() / 1000
399
400 const updateFakeVolume = (timestamp: number) => {
401 if (timestamp - lastUpdate >= updateInterval) {
402 const time = Date.now() / 1000 - startTime
403 const newBands = new Array(barCount)
404
405 for (let i = 0; i < barCount; i++) {
406 const waveOffset = i * 0.5
407 const baseVolume = Math.sin(time * 2 + waveOffset) * 0.3 + 0.5
408 const randomNoise = Math.random() * 0.2
409 newBands[i] = Math.max(0.1, Math.min(1, baseVolume + randomNoise))
410 }
411
412 // Only update if values changed significantly
413 let hasChanged = false
414 for (let i = 0; i < barCount; i++) {
415 if (Math.abs(newBands[i] - fakeVolumeBandsRef.current[i]) > 0.05) {
416 hasChanged = true
417 break
418 }
419 }
420
421 if (hasChanged) {
422 fakeVolumeBandsRef.current = newBands
423 setFakeVolumeBands(newBands)
424 }
425
426 lastUpdate = timestamp
427 }
428
429 fakeAnimationRef.current = requestAnimationFrame(updateFakeVolume)
430 }
431
432 fakeAnimationRef.current = requestAnimationFrame(updateFakeVolume)
433
434 return () => {
435 if (fakeAnimationRef.current) {
436 cancelAnimationFrame(fakeAnimationRef.current)
437 }
438 }
439 }, [demo, state, barCount])
440
441 // Use fake or real volume data based on demo mode
442 const volumeBands = useMemo(
443 () => (demo ? fakeVolumeBands : realVolumeBands),
444 [demo, fakeVolumeBands, realVolumeBands]
445 )
446
447 // Animation sequencing
448 const highlightedIndices = useBarAnimator(
449 state,
450 barCount,
451 state === "connecting"
452 ? 2000 / barCount
453 : state === "thinking"
454 ? 150
455 : state === "listening"
456 ? 500
457 : 1000
458 )
459
460 return (
461 <div
462 ref={ref}
463 data-state={state}
464 className={cn(
465 "relative flex justify-center gap-1.5",
466 centerAlign ? "items-center" : "items-end",
467 "bg-muted h-32 w-full overflow-hidden rounded-lg p-4",
468 className
469 )}
470 style={{
471 ...style,
472 }}
473 {...props}
474 >
475 {volumeBands.map((volume, index) => {
476 const heightPct = Math.min(
477 maxHeight,
478 Math.max(minHeight, volume * 100 + 5)
479 )
480 const isHighlighted = highlightedIndices?.includes(index) ?? false
481
482 return (
483 <Bar
484 key={index}
485 heightPct={heightPct}
486 isHighlighted={isHighlighted}
487 state={state}
488 />
489 )
490 })}
491 </div>
492 )
493 }
494)
495
496// Memoized Bar component to prevent unnecessary re-renders
497const Bar = React.memo<{
498 heightPct: number
499 isHighlighted: boolean
500 state?: AgentState
501}>(({ heightPct, isHighlighted, state }) => (
502 <div
503 data-highlighted={isHighlighted}
504 className={cn(
505 "max-w-[12px] min-w-[8px] flex-1 transition-all duration-150",
506 "rounded-full",
507 "bg-border data-[highlighted=true]:bg-primary",
508 state === "speaking" && "bg-primary",
509 state === "thinking" && isHighlighted && "animate-pulse"
510 )}
511 style={{
512 height: `${heightPct}%`,
513 animationDuration: state === "thinking" ? "300ms" : undefined,
514 }}
515 />
516))
517
518Bar.displayName = "Bar"
519
520// Wrap the main component with React.memo for prop comparison optimization
521const BarVisualizer = React.memo(
522 BarVisualizerComponent,
523 (prevProps, nextProps) => {
524 return (
525 prevProps.state === nextProps.state &&
526 prevProps.barCount === nextProps.barCount &&
527 prevProps.mediaStream === nextProps.mediaStream &&
528 prevProps.minHeight === nextProps.minHeight &&
529 prevProps.maxHeight === nextProps.maxHeight &&
530 prevProps.demo === nextProps.demo &&
531 prevProps.centerAlign === nextProps.centerAlign &&
532 prevProps.className === nextProps.className &&
533 JSON.stringify(prevProps.style) === JSON.stringify(nextProps.style)
534 )
535 }
536)
537
538BarVisualizerComponent.displayName = "BarVisualizerComponent"
539BarVisualizer.displayName = "BarVisualizer"
540
541export { BarVisualizer }
542