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)
}
}