import { useEffect, useRef } from 'react'; // Live input level of a microphone stream. export function MicMeter({ stream }: { stream: MediaStream | null }) { const barRef = useRef(null); useEffect(() => { if (!stream || stream.getAudioTracks().length === 0) return; const ctx = new AudioContext(); const src = ctx.createMediaStreamSource(stream); const analyser = ctx.createAnalyser(); analyser.fftSize = 1024; src.connect(analyser); const buf = new Float32Array(analyser.fftSize); let raf = 0; let level = 0; const loop = () => { analyser.getFloatTimeDomainData(buf); let peak = 0; for (const x of buf) peak = Math.max(peak, Math.abs(x)); level = Math.max(peak, level * 0.9); if (barRef.current) { barRef.current.style.width = `${Math.min(100, Math.sqrt(level) * 100)}%`; barRef.current.classList.toggle('hot', level > 0.9); } raf = requestAnimationFrame(loop); }; loop(); return () => { cancelAnimationFrame(raf); ctx.close(); }; }, [stream]); return (
); }