播放器播放模式有三種,順序播放,單曲循環,隨機播放,定義在vuex 中的字段為 mode。點擊切換播放模式的圖標。切換模式判斷是否為隨機播放,如果是隨機播放模式,則取得sequenceList 列表數組 。
首先分清楚 sequenceList 是歌單順序列表,顯示在界面上的,playlist 是根據播放模式改變的,順序播放時playlist 等於sequenceList ,隨機播放時playlist 為隨機數組列表
利用(shuffle)工具函數。將其隨機打亂重組賦值給vuex中的playlist。當改變playlist的時候需要重置 currentIndex ,因為playlist改變為隨機播放模式時。currentindex的索引指向的歌曲就不對了。 所以用 resetCurrentIndex 函數判斷當前歌曲的id 是否和列表中播放的歌曲的id相同,相同則重新賦值該索引,保證在正在播放當前歌曲的時候切換模式,當前歌曲不被改變
// util.js
// 返回最小與最大值之間的隨機數,包含最大最小值 function getRandomInt(min,max){ return Math.floor(Math.random() * (max - min+1) + min) } //將數組的副本循環隨機打亂重組一個新數組返回 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; }
vuex
export const playMode = { sequence:0, loop:1, random:2 } const state = { mode:playMode.sequence, } export default state
player.vue
<i :class="iconMode" @click="changeMode"></i> iconMode(){ return this.mode === playMode.sequence ? 'icon-sequence' : this.mode === playMode.loop ? 'icon-loop' : 'icon-random' //設置播放模式圖標 }, changeMode(){ let 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); //由於playlist 變成隨機模式,currentsong是根據currentindex 和playlist 改變的,需要保持currentindex 在隨機播放列表的正確位置,以確保當前播放歌曲不變 this.setPlayList(list); }, resetCurrentIndex(list){ let index = list.findIndex((item) => { return item.id === this.currentSong.id }) this.setCurrentIndex(index); },
單曲循環模式需要監聽audio 元素ended 事件,如果end 時模式為loop模式,則設置當前歌曲的currentTime為0,並重新播放,否則按照播放列表進行下一首播放(播放列表此時有可能是順序列表或者已改變為隨機列表)
在music-list 組件中,點擊隨機播放按鈕 提交actions 的randomPlay,設置playlist 為隨機播放列表,在選擇播放的時候判斷當前播放模式
function findIndex(list,song){ return list.findIndex((item) => { return item.id === song.id; }) } export const selectPlay = function({commit,state},{list,index}){ commit(types.SET_SEQUENCE_LIST, list) if (state.mode === playMode.random) { let randomList = shuffle(list) commit(types.SET_PLAYLIST, randomList) index = findIndex(randomList, list[index]) } else { commit(types.SET_PLAYLIST, list) } commit(types.SET_CURRENT_INDEX, index) commit(types.SET_FULL_SCREEN, true) commit(types.SET_PLAYING_STATE, true) }
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) }
<div class="play" ref="playBtn" @click="random"> random(){ this.randomPlay({ list:this.songs }) }, ...mapActions([ 'selectPlay', 'randomPlay' ])