简体   繁体   English

我希望在切换页面(标签)时继续播放音乐。 Next.js

[英]I want the music to continue playing as I switch pages(tabs). Next.js

I want to make music player in next.js application.我想在 next.js 应用程序中制作音乐播放器。 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;

You can determine your player in place where routing your project.您可以确定您的播放器在哪里路由您的项目。 In that class your player not stop when changing route在那 class 中,您的播放器在更改路线时不会停止

try using window.focus() in useEffect function尝试在 useEffect function 中使用 window.focus()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM