"use client"; import { useEffect, useRef } from "react"; export function AudioVisualizer({ stream, isRecording }: { stream: MediaStream | null; isRecording: boolean }) { const canvasRef = useRef(null); const animationRef = useRef(0); const analyserRef = useRef(null); const sourceRef = useRef(null); const audioCtxRef = useRef(null); useEffect(() => { if (!stream) return; if (!audioCtxRef.current) { audioCtxRef.current = new (window.AudioContext || (window as any).webkitAudioContext)(); } const audioCtx = audioCtxRef.current; if (audioCtx.state === "suspended") { audioCtx.resume(); } if (!analyserRef.current) { const analyser = audioCtx.createAnalyser(); analyser.fftSize = 256; analyser.smoothingTimeConstant = 0.8; analyserRef.current = analyser; } if (!sourceRef.current) { const source = audioCtx.createMediaStreamSource(stream); source.connect(analyserRef.current); sourceRef.current = source; } const canvas = canvasRef.current; if (!canvas) return; const ctx = canvas.getContext("2d"); if (!ctx) return; const analyser = analyserRef.current; const bufferLength = analyser.frequencyBinCount; const dataArray = new Uint8Array(bufferLength); const draw = () => { animationRef.current = requestAnimationFrame(draw); analyser.getByteFrequencyData(dataArray); ctx.clearRect(0, 0, canvas.width, canvas.height); const width = canvas.width; const height = canvas.height; const barWidth = (width / bufferLength) * 2.5; let barHeight; let x = 0; for (let i = 0; i < bufferLength; i++) { barHeight = dataArray[i]; // Create a smooth gradient const gradient = ctx.createLinearGradient(0, height, 0, 0); if (isRecording) { gradient.addColorStop(0, "#ef4444"); // Red 500 gradient.addColorStop(1, "#f87171"); // Red 400 } else { gradient.addColorStop(0, "#6366f1"); // Indigo 500 gradient.addColorStop(1, "#818cf8"); // Indigo 400 } ctx.fillStyle = gradient; // Add a glowing effect ctx.shadowBlur = isRecording ? 15 : 5; ctx.shadowColor = isRecording ? "rgba(239, 68, 68, 0.5)" : "rgba(99, 102, 241, 0.5)"; const actualHeight = (barHeight / 255) * height; ctx.fillRect(x, height - actualHeight, barWidth, actualHeight); x += barWidth + 2; } }; draw(); return () => { if (animationRef.current) cancelAnimationFrame(animationRef.current); ctx.clearRect(0, 0, canvas.width, canvas.height); }; }, [stream, isRecording]); return ( ); }