在 useEffect 卸载时暂停音频

时间:2021-02-13 18:27:49

标签: javascript reactjs audio use-effect

我想在组件卸载时停止在我的应用程序中播放音乐,但即使在另一个组件安装时它也在后台播放。 我正在尝试在 useEffect 上使用 “清理”功能,但似乎不行,我不知道为什么。 是不是应该运行返回“清理”函数中的代码然后卸载? 如果是这样,为什么我无法在卸载时暂停播放音频?

AudioPlayer.js: 这是所有逻辑发生的地方。

import React, { useEffect, useRef, useState, useContext } from "react";
import "./AudioPlayer.css";

//Functions
import getCurrentlyPlayingSong from "../../Functions/getCurrentlyPlayingSong";

//Context
import RefreshContext from "../../Context/RefreshContext";
import MainContentContext from "../../Context/MainContentContext";

//Imgs
import playButton from "./playButton.png";
import pauseButton from "./pauseButton.png";

export default function AudioPlayer(props) {
  const [musicIsPlaying, setMusicIsPlaying] = useState(false);
  const [isPreviewURL, setIsPreviewURL] = useState(false);

  const { mainContent } = useContext(MainContentContext);
  const { refresh } = useContext(RefreshContext);
  const audioRef = useRef(null);

  const playSong = async () => {
    if (!musicIsPlaying) {
      await audioRef.current.play();
      setMusicIsPlaying(true);
    }
  };

  const pauseSong = () => {
    if (musicIsPlaying) {
      audioRef.current.pause();
      playingRef.current = false;
      setMusicIsPlaying(false);
    }
  };

  const getSong = async () => {
    if (mainContent === "AddSongContent") {
      const response = await getCurrentlyPlayingSong();
      console.log(response);

      if (response.responseStatus === 200 && response.preview_url) {
        audioRef.current = new Audio(await response.preview_url);

        setIsPreviewURL(true);
      } else {
        setIsPreviewURL(false);
      }
    } else if (mainContent !== "AddSongContent") {
      if (props.preview_url) {
        audioRef.current = new Audio(await props.preview_url);

        setIsPreviewURL(true);
      } else {
        setIsPreviewURL(false);
      }
    }
  };

  useEffect(() => {
    getSong();

    
  }, [refresh]);

  useEffect(() => {
    getSong();

    return () => {
      pauseSong();
      console.log("Paused");
    };
    
  }, []);

  const AudioSwitch = () => {
    if (isPreviewURL && !musicIsPlaying) {
      return (
        <>
          <img
            className="playPauseButton"
            onClick={playSong}
            src={playButton}
            alt="play"
          ></img>
        </>
      );
    } else if (isPreviewURL && musicIsPlaying) {
      return (
        <>
          <img
            className="playPauseButton"
            onClick={pauseSong}
            src={pauseButton}
            alt="pause"
          ></img>
        </>
      );
    } else {
      return <p>No preview to play</p>;
    }
  };

  return (
    <div className="audioPlayer">
      <AudioSwitch />
    </div>
  );
}

0 个答案:

没有答案