MicProtocol / apps /web /src /components /audio-visualizer.tsx
Benaah's picture
Upload folder using huggingface_hub
fb12607 verified
Raw History Blame Contribute Delete
3.59 kB
"use client";
import { useEffect, useRef } from "react";
export function AudioVisualizer({ stream, isRecording }: { stream: MediaStream | null; isRecording: boolean }) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const animationRef = useRef<number>(0);
const analyserRef = useRef<AnalyserNode | null>(null);
const sourceRef = useRef<MediaStreamAudioSourceNode | null>(null);
const audioCtxRef = useRef<AudioContext | null>(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 (
<canvas
ref={canvasRef}
width={300}
height={100}
style={{
width: "100%",
maxWidth: "400px",
height: "100px",
borderRadius: "12px",
transition: "opacity 0.3s ease",
opacity: stream ? 1 : 0.3,
}}
/>
);
}