下面是当前代码
`` import { useState,useEffect,useRef } from“react”;从“react-icons/fa”导入{ FaPlay,FaPause,FaForward,FaBackward };
export default function Player() {
const [isPlaying, setIsPlaying] = useState(false);
const [currentTime, setCurrentTime] = useState(0);
const [duration, setDuration] = useState(0);
const [currentSongIndex, setCurrentSongIndex] = useState(0);
const audioRef = useRef<HTMLAudioElement>(null);
const songs = [
{ src: "/audio/fairtrade.mp3", title: "Fair Trade", },
{ src: "/audio/donotdisturb.mp3", title: "Do Not Disturb", },
{ src: "/audio/jimmycooks.mp3", title: "Jimmy Cooks", },];
useEffect(() => {
const audioPlayer = audioRef.current;
if (audioPlayer && isPlaying) {
audioPlayer.currentTime = currentTime;
audioPlayer.play();
} else if (audioPlayer) {
audioPlayer.pause();
}
// Add event listener for ended event
const handleNext = () => {
const nextSongIndex = currentSongIndex === songs.length - 1 ? 0 : currentSongIndex + 1;
setCurrentSongIndex(nextSongIndex);
setIsPlaying(false);
setCurrentTime(0);
};
audioPlayer.addEventListener("ended", handleNext);
// Cleanup function to remove event listener
return () => {
audioPlayer.removeEventListener("ended", handleNext);
};
}, [currentSongIndex, isPlaying]);
useEffect(() => {
const audioPlayer = audioRef.current;
if (audioPlayer) {
audioPlayer.src = songs[currentSongIndex].src;
audioPlayer.load();
}
}, [currentSongIndex]);
const togglePlay = () => {
setIsPlaying(!isPlaying);
};
const handleTimeUpdate = () => {
const audioPlayer = audioRef.current;
if (audioPlayer) {
setCurrentTime(audioPlayer.currentTime);
setDuration(audioPlayer.duration);
}
};
const handleNext = () => {
const nextSongIndex = currentSongIndex === songs.length - 1 ? 0 : currentSongIndex + 1;
setCurrentSongIndex(nextSongIndex);
setIsPlaying(false);
setCurrentTime(0);
};
const handlePrevious = () => {
const previousSongIndex = currentSongIndex === 0 ? songs.length - 1 : currentSongIndex - 1;
setCurrentSongIndex(previousSongIndex);
setIsPlaying(false);
setCurrentTime(0);
};
const handleSeekBarChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const audioPlayer = audioRef.current;
if (audioPlayer) {
audioPlayer.currentTime = Number(event.target.value);
setCurrentTime(audioPlayer.currentTime);
}
};``
Error from Vercel
我该怎么做才能改变这一点。我一直在努力,但我似乎不明白我的错误在哪里。
第33和37行是错误的
我试图在访问第33和37行的audioPlayer对象之前添加一个检查,但它不起作用。
编辑
所以对不起我的菜鸟问题,所有我必须做的是audioPlayer?.addEventListener("ended", handleNext);
通过放置一个?
1条答案
按热度按时间lsmepo6l1#
将
?
添加到第33和37行,使其成为audioPlayer?.addEventListener("ended", handleNext);
完全修复了错误。