Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

238
Visualizações
stopping audio when switching pages with react router

I have the code below that plays or pauses audio within a function of react. Currently, the audio plays even when I navigate to other pages like /manage or /upload. However, I want the audio to completely stop when I navigate to other pages.

How can I do this?

codde:

  const [playing, setPlaying] = useState(false);
  const [playingAudio, setPlayingAudio] = useState([]);
  
  const location = useLocation();

  const handleAudioPlay = (customer_id, sound_id, state) => {
    

    var data = {
      "current-user": location.state.customer_id || props.customer_id,
      "customer-id": customer_id,
      "sound-id": sound_id
    };
    
    /*
    if(state) {
      axios.post(`http://localhost:2000/files/get-temporary-url`, data).then(function(result) {
        var audio = new Audio(result.data)
        audio.crossOrigin = 'anonymous';
        setPlayingAudio(audio)
        if(playing) {
          audio.pause()
        }
        else {
          audio.play()
          setPlaying(true)
          audio.addEventListener('ended', function() {
            setPlaying(false)
            }, false);
        }
      });;
    */
    
    
    if(state) {
      axios.post(`/files/get-temporary-url`, data).then(function(result) {
        var audio = new Audio(result.data)
        audio.crossOrigin = "anonymous";
        setPlayingAudio(audio)
        if(playing) {
          audio.pause()
        }
        else {
          audio.play()
          setPlaying(true)
          audio.addEventListener('ended', function() {
            setPlaying(false)
            }, false);
        }
      });;
    
    }
    else {
      playingAudio.pause()
      setPlaying(false)
    }
  
  }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think you could use an useEffect hook to pause the audio and unsubscribe any event listeners when the component unmounts.

Use a mounting useEffect hook that returns a cleanup function to be run when the component unmounts.

Example:

const [playing, setPlaying] = useState(false);
const [playingAudio, setPlayingAudio] = useState([]);

const location = useLocation();

const handldEnded = () => setPlaying(false);

const handleAudioPlay = (customer_id, sound_id, state) => {
  const data = {
    "current-user": location.state.customer_id || props.customer_id,
    "customer-id": customer_id,
    "sound-id": sound_id
  };

  if (state) {
    axios.post(`/files/get-temporary-url`, data).then(function(result) {
      const audio = new Audio(result.data);
      audio.crossOrigin = "anonymous";
      setPlayingAudio(audio);
      if (playing) {
        audio.pause();
      } else {
        audio.play();
        setPlaying(true);
        audio.addEventListener('ended', handldEnded, false);
      }
    });
  } else {
    playingAudio.pause();
    setPlaying(false);
  }
};

useEffect(() => {
  return () => {
    playingAudio.removeEventListener("ended", handldEnded, false);
    playingAudio.pause();
  };
}, []);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda