I want to make music player in next.js application. How do I prevent the playing track from stopping when switching between pages? In short, I want the music to continue playing as I switch pages(tabs).
My code is here;
import React, { useState, useEffect } from "react";
const useAudio = url => {
const [audio, setAuido]: any = useState();
const [playing, setPlaying] = useState(false);
const toggle: any = () => setPlaying(!playing);
useEffect(() => {
if (typeof window !== 'undefined') {
setAuido(new Audio(url))
}
}, [])
useEffect(() => {
if (audio !== undefined) {
playing ? audio.play() : audio.pause();
}
}, [playing]);
useEffect(() => {
if (audio === undefined) {
return;
}
audio.addEventListener('ended', () => setPlaying(false));
return () => {
audio.removeEventListener('ended', () => setPlaying(false));
};
}, [audio]);
return [playing, toggle];
};
const Player = ({ url }) => {
const [playing, toggle] = useAudio(url);
return (
<div>
<button onClick={toggle}>{playing ? "Pause" : "Play"}</button>
{/* <audio controls autoPlay={playing}>
<source src="/sound/sound.mp3" type="audio/mpeg" />
</audio> */}
</div>
);
};
export default Player;
CodePudding user response:
You can determine your player in place where routing your project. In that class your player not stop when changing route
CodePudding user response:
try using window.focus() in useEffect function