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)
}
}
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();
};
}, []);