APlayer 跳转页面保持音乐播放进度

想给博客加个音频播放的插件作为背景音乐,但是在博客内跳转的时候音乐会中断并重新加载,参考了网易云音乐网页版的解决办法就是所有页面都在前端通过Ajax动态加载,并不会跳转网页,所以音乐播放不会中断。但是改Hexo源码的话不太可行,想到一个办法就是每次跳转前记录进度并在下次加载网页时读取

添加APlayer部分参考Hexo NexT主题中添加网页音乐播放器功能

后来发现个很好用的插件MetingJS,可以直接解析网易云音乐等各网络平台的歌曲

在 themes/next/layout/_layout.swig 添加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!-- require APlayer -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css">
<script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script>
<!-- require MetingJS -->
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

<div style="opacity:0.7">
<meting-js
server="netease"
type="playlist"
id="2486559481"
fixed="true"
volume="0.3"
order="random"
>
</meting-js>
</div>

id对应歌单,其他配置项详见文档

然后要获取APlayer对象来控制音乐播放,document.querySelector('meting-js').aplayer,在浏览器控制台可以成功获取,但写在HTML源码中就无法获得,应该是执行该代码时meting还未来得及初始化aplayer对象,后来试了很多办法,终于解决,即监听对象值的变化

1
2
3
4
5
6
7
8
9
10
11
12
ap = null
Object.defineProperty(document.querySelector('meting-js'),"aplayer",{
set: function(aplayer) {
ap=aplayer
ready();
}
});

function ready(){
ap.list.switch(0);
ap.play();
}

还有个小坑:HTML5中Audio元素在chrome中自动播放报错Uncaught (in promise) DOMException的解决方法

最后完整添加到 themes/next/layout/_layout.swig 的代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<!-- require APlayer -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css">
<script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script>
<!-- require MetingJS -->
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

<div style="opacity:0.7">
<meting-js
server="netease"
type="playlist"
id="2486559481"
fixed="true"
volume="0.3"
order="random"
>
</meting-js>
</div>

<script>
ap = null
Object.defineProperty(document.querySelector('meting-js'),"aplayer",{
set: function(aplayer) {
ap=aplayer
ready();
}
});

isRecover = false;
function ready(){
ap.on('canplay', function () {
if(!isRecover){
if(localStorage.getItem("musicIndex") != null){
musicIndex = localStorage.getItem("musicIndex");
musicTime = localStorage.getItem("musicTime");
if(ap.list.index != musicIndex){
ap.list.switch(musicIndex);
}else{
ap.seek(musicTime);
ap.play();
localStorage.clear();
isRecover = true;
}
}else{
isRecover = true;
}
}
});
}

window.onbeforeunload = function(event) {
if(!ap.audio.paused){
musicIndex = ap.list.index;
musicTime = ap.audio.currentTime;
localStorage.setItem("musicIndex",musicIndex);
localStorage.setItem("musicTime",musicTime);
}
};
</script>

参考

Hexo NexT主题中添加网页音乐播放器功能

APlayer

MetingJS