javascript - 将音频 isPlaying 状态设置为当前音频唯一
问题描述
我正在获取一堆曲目,每个曲目都有自己的按钮来播放每个曲目。我可以单击它们进行播放,然后再次单击以暂停音频,但是如果我尝试播放新音频而不暂停当前正在播放的音频,除非我双击,否则它将不会播放,因为 isPlaying 状态将设置为 false(此是我切换播放/暂停的方式)。我希望能够在 isPlaying 为真时单击新音频,而不是将该状态更改为假(但如果我单击同一个按钮两次,仍然能够暂停当前音频)。谢谢!
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);
};
推荐阅读
- python - 在python中使用一个testclass函数到另一个testclass
- r - 错误:参数数量不正确 (5),“rlang_quos_interp”应为 4
- javascript - OwlCarousel2 显示空白幻灯片,而其他所有 HTML 标记都显示正常
- date - 谷歌表 - 脚本/条件格式 > 根据日期设置列的背景颜色 1/今天之前 = 红色 2/今天 = 黄色
- java - 已删除的实例传递给合并
- jsp - jsp 页面显示 javax.servlet.ServletException: java.lang.OutOfMemoryError: Java heap space
- r - Creating all possible combinations of items and doing calculations simultaneously
- python - Django 显示的日期时间与系统日期时间不同
- android - 如何展示原生广告?
- jquery - JQuery:触发器('change')与触发器('change.select2')