超好看的音乐播放器组件
1.先看效果
2.源代码
"use client"
import { useState, useRef, useEffect } from "react"
import { motion, AnimatePresence } from "framer-motion"
import { Play, Pause, SkipBack, SkipForward, Volume2 } from "lucide-react"
import { Slider } from "@/components/ui/slider"
export default function MusicPlayer() {
const [isPlaying, setIsPlaying] = useState(false)
const [currentTime, setCurrentTime] = useState(0)
const [duration, setDuration] = useState(0)
const [volume, setVolume] = useState(1)
const audioRef = useRef
useEffect(() => {
if (audioRef.current) {
audioRef.current.volume = volume
}
}, [volume])
const togglePlay = () => {
if (audioRef.current) {
if (isPlaying) {
audioRef.current.pause()
} else {
audioRef.current.play()
}
setIsPlaying(!isPlaying)
}
}
const handleTimeUpdate = () => {
if (audioRef.current) {
setCurrentTime(audioRef.current.currentTime)
setDuration(audioRef.current.duration)
}
}
const handleSeek = (newValue: number[]) => {
if (audioRef.current) {
audioRef.current.currentTime = newValue[0]
setCurrentTime(newValue[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 (
className="w-48 h-48 rounded-full overflow-hidden mb-6" animate={{ rotate: isPlaying ? 360 : 0 }} transition={{ repeat: Infinity, duration: 3, ease: "linear" }} > src="/placeholder.svg?height=192&width=192" alt="Album cover" className="w-full h-full object-cover" />
Song Title
Artist Name
value={[currentTime]} max={duration} step={0.1} onValueChange={handleSeek} className="w-full" /> {formatTime(currentTime)} {formatTime(duration)}
whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }} className="text-white" >
whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }} className="bg-white text-purple-800 rounded-full p-3" onClick={togglePlay} > {isPlaying ? ( key="pause" initial={{ opacity: 0, scale: 0.5 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: 0.5 }} transition={{ duration: 0.2 }} > ) : ( key="play" initial={{ opacity: 0, scale: 0.5 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: 0.5 }} transition={{ duration: 0.2 }} > )}
whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }} className="text-white" >
value={[volume]} max={1} step={0.01} onValueChange={(newValue) => setVolume(newValue[0])} className="w-full" />
)
}
扫描二维码分享
评论区
请登录后发表评论。