[英]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.