实现站点全局音乐播放

需求:在站内任意一个页面播放音乐,然后不管跳转到站内的任何页,音乐都能继续播放;

就比如是这样的:在这里播放的音乐即使返回首页,跳转到站内的其它页,音乐继续播放;

这是一个最简单的办法:

<div style="margin: 0; padding: 0;">
    <div id="player-container"
        style="width: 100%; background-color: transparent; border: none; display: flex; justify-content: center; align-items: center; padding: 0; margin: 0; box-sizing: border-box;">
        <audio id="audioPlayer" controls="" style="width: 100%; max-width: 300px; margin: 0;">
            <source src="https://zzhanzhang.top/wp-content/uploads/1.mp3" type="audio/mpeg">
        </audio>
    </div>
    <script>
        const audioPlayer = document.getElementById('audioPlayer');
        let isPlaying = sessionStorage.getItem('isPlaying') === 'true';

        if (isPlaying) {
            audioPlayer.play();
        }

        const savedTime = sessionStorage.getItem('audioCurrentTime');
        if (savedTime) {
            audioPlayer.currentTime = parseFloat(savedTime);
        }

        audioPlayer.addEventListener('play', () => {
            isPlaying = true;
            sessionStorage.setItem('isPlaying', 'true');
        });

        audioPlayer.addEventListener('pause', () => {
            isPlaying = false;
            sessionStorage.setItem('isPlaying', 'false');
        });

        audioPlayer.addEventListener('timeupdate', () => {
            sessionStorage.setItem('audioCurrentTime', audioPlayer.currentTime);
        });

        window.addEventListener('beforeunload', () => {
            sessionStorage.setItem('audioCurrentTime', audioPlayer.currentTime);
            sessionStorage.setItem('isPlaying', isPlaying);
        });
    </script>
</div>

一些问题

音频加载时间仍然较长,在页面跳转时尤其明显。在PC端播放器位于侧边栏所以并没什么影响,但在由于手机上的页面响应是自上而下的,而播放器位于页面底部。为了继续播放音乐,必须先加载完上面的内容,这导致了播放的延迟。

解决办法:压缩音频,被压缩至920KB,压缩后的音质听起来还是别有一番感觉;
使用预加载:这似乎并没有多大作用,在手机上,仍然需要页面浏览到播放器的位置后才会自动继续播放音乐;