Open History to see the last commit
1import { useEffect, useRef } from 'react'
2
3export function AudioSparkline({
4 getData,
5 color,
6 label,
7}: {
8 getData: () => Uint8Array
9 color: string
10 label: string
11}) {
12 const canvasRef = useRef<HTMLCanvasElement>(null)
13 const animationRef = useRef<number | null>(null)
14
15 useEffect(() => {
16 const canvas = canvasRef.current
17 if (!canvas) return
18
19 const ctx = canvas.getContext('2d')
20 if (!ctx) return
21
22 function draw() {
23 const data = getData()
24 const width = canvas!.width
25 const height = canvas!.height
26
27 ctx!.fillStyle = '#1f2937'
28 ctx!.fillRect(0, 0, width, height)
29
30 ctx!.strokeStyle = color
31 ctx!.lineWidth = 1
32 ctx!.beginPath()
33
34 const step = Math.max(1, Math.floor(data.length / width))
35
36 for (let i = 0; i < width; i++) {
37 const dataIndex = Math.min(i * step, data.length - 1)
38 const value = data[dataIndex] ?? 128
39 const y = height - (value / 255) * height
40
41 if (i === 0) {
42 ctx!.moveTo(i, y)
43 } else {
44 ctx!.lineTo(i, y)
45 }
46 }
47
48 ctx!.stroke()
49
50 ctx!.strokeStyle = '#4b5563'
51 ctx!.setLineDash([2, 2])
52 ctx!.beginPath()
53 ctx!.moveTo(0, height / 2)
54 ctx!.lineTo(width, height / 2)
55 ctx!.stroke()
56 ctx!.setLineDash([])
57
58 animationRef.current = requestAnimationFrame(draw)
59 }
60
61 draw()
62
63 return () => {
64 if (animationRef.current) {
65 cancelAnimationFrame(animationRef.current)
66 }
67 }
68 }, [getData, color])
69
70 return (
71 <div className="flex items-center gap-2">
72 <span className="text-xs text-gray-500 w-12">{label}</span>
73 <canvas
74 ref={canvasRef}
75 width={200}
76 height={40}
77 className="rounded border border-gray-700"
78 />
79 </div>
80 )
81}