首页 > 解决方案 > 将音频 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;

标签: javascriptreactjsaudiostate

解决方案


你可以试试这个:

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

推荐阅读