[英]I want the music to continue playing as I switch pages(tabs). Next.js
我想在 next.js 應用程序中制作音樂播放器。 切換頁面時如何防止播放曲目停止? 簡而言之,我希望在切換頁面(標簽)時繼續播放音樂。
我的代碼在這里;
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;
您可以確定您的播放器在哪里路由您的項目。 在那 class 中,您的播放器在更改路線時不會停止
嘗試在 useEffect function 中使用 window.focus()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.