"use client"; import { useState, useRef, useEffect } from "react"; import { Play, Pause, Volume2, VolumeX } from "lucide-react"; import { Slider } from "@/components/ui/slider"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; interface AudioPlayerProps { src: string; className?: string; autoplay?: boolean; onPlayStateChange?: (isPlaying: boolean) => void; } export function AudioPlayer({ src, className, autoplay = false, onPlayStateChange }: AudioPlayerProps) { const [isPlaying, setIsPlaying] = useState(autoplay); const [duration, setDuration] = useState(0); const [currentTime, setCurrentTime] = useState(0); const [volume, setVolume] = useState(1); const [isMuted, setIsMuted] = useState(false); const audioRef = useRef(null); useEffect(() => { const audio = audioRef.current; if (!audio) return; if (autoplay) { audio.play().catch(() => { /* Autoplay blocked by browser */ }); } const setAudioData = () => { setDuration(audio.duration); setVolume(audio.volume); }; const setAudioTime = () => { setCurrentTime(audio.currentTime); }; const handleEnded = () => { setIsPlaying(false); onPlayStateChange?.(false); }; // Add event listeners audio.addEventListener("loadeddata", setAudioData); audio.addEventListener("timeupdate", setAudioTime); audio.addEventListener("ended", handleEnded); return () => { audio.removeEventListener("loadeddata", setAudioData); audio.removeEventListener("timeupdate", setAudioTime); audio.removeEventListener("ended", handleEnded); }; }, [src, autoplay, onPlayStateChange]); const togglePlay = () => { const audio = audioRef.current; if (!audio) return; if (isPlaying) { audio.pause(); onPlayStateChange?.(false); } else { audio.play(); onPlayStateChange?.(true); } setIsPlaying(!isPlaying); }; const toggleMute = () => { const audio = audioRef.current; if (!audio) return; audio.muted = !isMuted; setIsMuted(!isMuted); }; const handleVolumeChange = (value: number[]) => { const audio = audioRef.current; if (!audio) return; const newVolume = value[0]; audio.volume = newVolume; setVolume(newVolume); if (newVolume > 0 && isMuted) { setIsMuted(false); audio.muted = false; } }; const handleSeek = (value: number[]) => { const audio = audioRef.current; if (!audio) return; audio.currentTime = value[0]; setCurrentTime(value[0]); }; const formatTime = (time: number) => { const minutes = Math.floor(time / 60); const seconds = Math.floor(time % 60); return `${minutes}:${seconds.toString().padStart(2, "0")}`; }; return (
); }