歌曲列表

点击歌曲,添加歌曲到播放列表并播放歌曲。

核心精髓是点歌的时候把这首歌放到列表里,也就是一个数组里。

因此需要修改GlobalMusic类:

之后修改播放器类中的singPlay方法:

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
singPlay(song: SongItemType) {
// some方法来检查数组里的数据是否有一个与song相等
const inList: boolean = this.currentSong.playList.some((item) => {item.id === song.id})
if (inList) {
// song在列表里 -> 是否是正在播放的
if (this.currentSong.url === song.url) {
this.player?.play()
} else {
// 设置新的索引
this.currentSong.playIndex = this.currentSong.playList.findIndex(item => item.id === song.id)
// 切换歌曲
this.changeSong()
}
} else {
// song不在列表里 -> 添加歌曲到列表+切换歌曲
this.currentSong.playList.unshift(song) // 在数组前面插入数据
this.currentSong.playIndex = 0 // 播放索引重置为0
// 切换歌曲?
this.changeSong()
}
}
// 切换歌曲 -> 重置播放器
async changeSong() {
await this.player?.reset()
this.currentSong.duration = 0
this.currentSong.time = 0
this.currentSong.img = this.currentSong.playList[this.currentSong.playIndex].img
this.currentSong.name = this.currentSong.playList[this.currentSong.playIndex].name
this.currentSong.author = this.currentSong.playList[this.currentSong.playIndex].author
this.currentSong.url = this.currentSong.playList[this.currentSong.playIndex].url
this.player!.url = this.currentSong.url
}

播放和暂停

播放已经实现了,暂停之前没有代码实现,暂停代码:

在播放暂停的代码部分按情况调用函数即可。

上一首下一首

要实现上一首下一首的功能,直接更改索引即可。另外要注意索引值不要越界。

切换播放模式

播放模式一般有单曲循环、列表循环、随机播放等模式。

随机播放的话,让播放索引随机取值即可,列表播放的话就一如既往地播放索引+1或-1。

由于涉及到这首歌播完接着播哪首的问题,需要再监听一个状态completed,代表本首歌播完执行什么操作。

生成随机索引值用以下函数:

之后要修改上一首、下一首的函数内容:

  • 上一首:

  • 下一首:

播放列表

完善播放列表弹窗里的功能。

播放列表显示歌曲数量:

注意上面的字符串用的是反引号,这样能直接在字符串里使用变量。

给播放列表的每首歌加上.onClick来调用singPlay方法。

每首歌侧滑出现删除按钮:使用.swipeAction

实现删除按钮对应的功能,需要在AvPlayerManager中新增删除函数。

removeSong函数的实现: