'How to keep playing the current music when switch between Route (Reactjs)
I have a function that plays music on the page. It look like this
const useAudio = url => {
const [audio] = useState(new Audio(url));
const [playing, setPlaying] = useState(false);
const toggle = () => { setPlaying(!playing); };
useEffect(() => {
playing ? audio.play() : audio.pause();
},
[playing, audio]
);
useEffect(() => {
audio.addEventListener('ended', () => setPlaying(false));
return () => {
audio.removeEventListener('ended', () => setPlaying(false));
};
}, [audio]);
return [playing, toggle];
};
And a button to toggle the music:
...
<button onClick={toggle}>{playing ? "Pause" : "Play"</button>
...
I'm using React Router to navigate between pages, but I don't know how to keep the music playing the same as before the page was switched.
I have an idea that I will use Session Storage to store states from the audio, but I don't know how to get it, like current playing time. Or how to keep it playing from that time. Thanks for your help!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
