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

我正在获取一堆曲目,每首曲目都有自己的按钮来播放每首曲目。我可以点击它们播放,然后再次点击暂停音频,但如果我尝试播放新音频而不暂停当前正在播放的音频,除非我双击它,否则它不会播放,因为 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);

    setCurretId(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>

  );

};




德玛西亚99
浏览 113回答 1
1回答

哈士奇WWW

你可以试试这个:const handleClickPlay = (track) => {&nbsp; setCurrentSong(track);&nbsp; setCurrentId(track.id);&nbsp; if (track.id === currentId) togglePlay();&nbsp; else setIsPlaying(true);};
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript