【音乐App】—— Vue-music 项目学习笔记:播放器内置组件开发(二)
前言:以下内容均为学习慕课网高级实战课程的实践爬坑笔记。
项目github地址:https://github.com/66Web/ljq_vue_music,欢迎Star。
![]() |
![]() |
播放模式切换 | 歌词滚动显示 |
一、播放器模式切换功能实现 |
按钮样式随模式改变而改变
- 动态绑定iconMode图标class:
<i :class="iconMode"></i>
import {playMode} from '@/common/js/config' iconMode(){ return this.mode === playMode.sequence ? 'icon-sequence' : this.mode === playMode.loop ? 'icon-loop' : 'icon-random' }
- 给按钮添加点击事件,通过mapGetters获取mode,通过mapMutaions修改:
<div class="icon i-left" @click="changeMode">
changeMode(){ const mode = (this.mode + 1) % 3 this.setPlayMode(mode) } setPlayMode: 'SET_PLAY_MODE'
播放列表顺序随模式改变而改变
- common->js目录下:创建util.js,提供工具函数
function getRandomInt(min, max){ return Math.floor(Math.random() * (max - min + 1) + min) } //洗牌: 遍历arr, 从0-i 之间随机取一个数j,使arr[i]与arr[j]互换 export function shuffle(arr){ let _arr = arr.slice() //改变副本,不修改原数组 避免副作用 for(let i = 0; i<_arr.length; i++){ let j = getRandomInt(0, i) let t = _arr[i] _arr[i] = _arr[j] _arr[j] = t } return _arr }
- 通过mapGetters获取sequenceList,在changeMode()中判断mode,通过mapMutations修改playlist
changeMode(){ const mode = (this.mode + 1) % 3 this.setPlayMode(mode) let list = null if(mode === playMode.random){ list = shuffle(this.sequenceList) }else{ list = this.sequenceList } this.resetCurrentIndex(list) this.setPlayList(list) }
播放列表顺序改变后当前播放歌曲状态不变
- findIndex找到当前歌曲id值index,通过mapMutations改变currentIndex,保证当前歌曲的id不变
resetCurrentIndex(list){ let index = list.findIndex((item) => { //es6语法 findIndex return item.id === this.currentSong.id }) this.setCurrentIndex(index) }
- 坑:CurrentSong发生了改变,会触发watch中监听的操作,如果当前播放暂停,改变模式会自动播放
- 解决:添加判断,如果当前歌曲的id不变,认为CurrentSong没变,不执行任何操作
currentSong(newSong, oldSong) { if(newSong.id === oldSong.id) { return } this.$nextTick(() => { //确保DOM已存在 this.$refs.audio.play() }) }
当前歌曲播放完毕时自动切换到下一首或重新播放
- 监听audio派发的ended事件:@ended="end"
end(){ if(this.mode === playMode.loop){ this.loop() }else{ this.next() } }, loop(){ this.$refs.audio.currentTime = 0 this.$refs.audio.play() }
“随机播放全部”按钮功能实现
- music-list.vue中给按钮监听点击事件
@click="random"
- actions.js中添加randomPlay action
import {playMode} from '@/common/js/config' import {shuffle} from '@/common/js/util' export const randomPlay = function ({commit},{list}){ commit(types.SET_PLAY_MODE, playMode.random) commit(types.SET_SEQUENCE_LIST, list) let randomList = shuffle(list) commit(types.SET_PLAYLIST, randomList) commit(types.SET_CURRENT_INDEX, 0) commit(types.SET_FULL_SCREEN, true) commit(types.SET_PLAYING_STATE, true) }
- music-list.vue中定义random方法应用randomPlay
random(){ this.randomPlay({ list: this.songs }) } ...mapActions([ 'selectPlay', 'randomPlay' ])
- 坑:当点击了“随机播放全部”之后,再选择歌曲列表中指定的一首歌,播放的不是所选择的歌曲
- 原因:切换了随机播放之后,当前播放列表的顺序就不是歌曲列表的顺序了,但选择歌曲时传给currentIndex的index还是歌曲列表的index