gpt4 book ai didi

javascript - 将音频isPlaying状态设置为当前音频唯一

转载 作者:行者123 更新时间:2023-12-03 01:08:40 25 4
gpt4 key购买 nike

我正在获取一堆音轨,每个音轨都有一个播放每个音轨的按钮。我可以单击它们以播放,然后再次单击以暂停音频,但是如果我尝试播放新音频而不暂停当前正在播放的音频,则除非我双击,否则它不会播放,因为isPlaying状态将设置为false(这是我切换播放/暂停的方式)。
我希望能够在isPlaying为true时单击一个新音频,并且不希望将该状态更改为false(但是如果我单击同一按钮两次,则仍然可以暂停当前音频)。谢谢!

const App = () => {
const [tracks, setTracks] = React.useState(null);
const [currentSong, setCurrentSong] = useState(null);
const [currentId, setCurrentId] = useState(null);
const [isPlaying, setIsPlaying] = useState(false);

const audio = useRef();

// toggle function for toggling whether audio is played or paused
const togglePlay = () => {
setIsPlaying(!isPlaying);
};

// onClick function for handling currentSong and isPlaying state
const handleClickPlay = (track) => {
setCurrentSong(track);
setCurrentId(track.id);
setIsPlaying(true);
if (isPlaying) {
togglePlay();
}
};

React.useEffect(() => {
if (currentSong) {
if (isPlaying) {
audio.current.play();
} else {
audio.current.pause();
}
}
}, [currentSong, isPlaying]);

React.useEffect(() => {
if (isPlaying) {
if (setCurrentSong) {
setIsPlaying(true);
}
}
}, []);

React.useEffect(() => {
fetch("/album.json")
.then((response) => response.json())
.then((data) => {
const tracks = Object.values(data.entities.tracks);
setTracks(tracks);
});
}, []);
if (!tracks) {
return <div>Loading...</div>;
}

console.log(currentSong);
console.log(currentId);
console.log(isPlaying);

return (
<div>
{currentSong && (
<audio src={currentSong.stems.full.lqMp3Url} ref={audio}></audio>
)}

<table>
<tbody>
{tracks.map((track) => (
<TrackRow
track={track}
handleClickPlay={handleClickPlay}
isPlaying={isPlaying}
id={currentId}
currentSong={currentSong}
trackMatchId={() => currentSong === currentId}
/>
))}
</tbody>
</table>
</div>
);
};
export default App;


const TrackRow = ({
track,
handleClickPlay,
currentSong,
isPlaying,
id,
trackMatchId,
}) => {
const handleClick = () => handleClickPlay(track);

return (
<tr>
<button onClick={handleClick}>{isPlaying ? "pause" : "play"}</button>

<td>{track.title}</td>
</tr>
);
};
export default TrackRow;

最佳答案

您可以尝试以下方法:

const handleClickPlay = (track) => {
setCurrentSong(track);
setCurrentId(track.id);
if (track.id === currentId) togglePlay();
else setIsPlaying(true);
};

关于javascript - 将音频isPlaying状态设置为当前音频唯一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64249375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com