前言
本文存在多張gif演示圖,建議在
wifi
環(huán)境下閱讀??
最近在做網(wǎng)易云音樂微信小程序開源項目的時候,關(guān)于播放器功能
參考了一些成熟的微信小程序,如網(wǎng)易云音樂小程序
和QQ音樂小程序
,但是發(fā)現(xiàn)這些小程序端
的播放器相對于APP端
來說較簡單,只支持一些基礎(chǔ)功能,那么是否可以在小程序端實現(xiàn)一個功能相對完善的音樂播放器呢??
通過調(diào)研一些音樂類APP,一個功能相對完善的音樂播放器大概需要支持以下幾個功能:
- 歌曲切換
- 進度條拖拽
- 快進?快退?
- 歌詞同步
- 歌詞跳轉(zhuǎn)
- 歌曲后臺播放(微信小程序)

對播放器按照功能進行拆分,大致結(jié)構(gòu)如下圖所示??主要分為控制區(qū)域
和歌詞區(qū)域

下面來一起實現(xiàn)吧??
初始化全局播放器
頁面切換時也需要保持音樂持續(xù)播放,因此需要對播放器進行全局狀態(tài)管理,由于VueX對ts并不友好,此處引入Pinia
狀態(tài)管理 Pinia
全局初始化Audio
實例:uni.createInnerAudioContext() Audio實例uni.getBackgroundAudioManager() 微信小程序后臺播放
由于直接在Pinia中初始化Audio實例會出現(xiàn)
切換歌曲創(chuàng)建多個實例
的bug,因此通過在App.vue
文件中初始化實例實現(xiàn)全局唯一Audio實例
initPlayer
創(chuàng)建全局Audio實例
// initPlayer.ts
// 全局初始化audio實例,解決微信小程序無法正常使用pinia調(diào)用audio實例的bug
let innerAudioContext:any
export const createPlayer = () => {return innerAudioContext = uni.getBackgroundAudioManager ?uni.getBackgroundAudioManager() : uni.createInnerAudioContext()
}
export const getPlayer = () => innerAudioContext
usePlayerStore
統(tǒng)一管理播放器狀態(tài)和方法,useInitPlayer
初始化播放器并進行實時監(jiān)聽
// Pinia
import { defineStore, storeToRefs } from 'pinia';
import { onUnmounted, watch } from 'vue';
import { getSongUrl, getSongDetail, getSongLyric } from '../config/api/song';
import type { Song, SongUrl } from '../config/models/song';
import { getPlayer } from '../config/utils/initPlayer';
export const usePlayerStore = defineStore({id: 'Player',state: () => ({// audio: uni.createInnerAudioContext(), // Audio實例loopType: 0, // 循環(huán)模式 0 列表循環(huán) 1 單曲循環(huán) 2隨機播放playList: [] as Song[], // 播放列表showPlayList: false, // 播放列表顯隱id: 0,// 當(dāng)前歌曲idurl: '',// 歌曲urlsongUrl: {} as SongUrl,song: {} as Song,isPlaying: false, // 是否播放中isPause: false, // 是否暫停sliderInput: false, // 是否正在拖動進度條ended: false, // 是否播放結(jié)束muted: false, // 是否靜音currentTime: 0, // 當(dāng)前播放時間duration: 0, // 總播放時長currentLyric: null, // 解析后歌詞數(shù)據(jù)playerShow: false, // 控制播放器顯隱}),getters: {playListCount: (state) => { // 播放列表歌曲總數(shù)return state.playList.length;},thisIndex: (state) => { // 當(dāng)前播放歌曲索引return state.playList.findIndex((song) => song.id === state.id);},nextSong(state): Song { // 切換下一首const { thisIndex, playListCount } = this;if (thisIndex === playListCount - 1) {// 最后一首return state.playList[0];} else {// 切換下一首const nextIndex: number = thisIndex + 1;return state.playList[nextIndex];}},prevSong(state): Song { // 返回上一首const { thisIndex } = this;if (thisIndex === 0) {// 第一首return state.playList[state.playList.length - 1];} else {// 返回上一首const prevIndex: number = thisIndex - 1;return state.playList[prevIndex];}}},actions: {// 播放列表里面添加音樂pushPlayList(replace: boolean, ...list: Song[]) {if (replace) {this.playList = list;return;}list.forEach((song) => {// 篩除重復(fù)歌曲if (this.playList.filter((s) => s.id == song.id).length <= 0) {this.playList.push(song);}})},// 刪除播放列表中某歌曲deleteSong(id: number) {this.playList.splice(this.playList.findIndex((s) => s.id == id),1)},// 清空播放列表clearPlayList() {this.songUrl = {} as SongUrl;this.url = '';this.id = 0;this.song = {} as Song;this.isPlaying = false;this.isPause = false;this.sliderInput = false;this.ended = false;this.muted = false;this.currentTime = 0;this.playList = [] as Song[];this.showPlayList = false;const audio = getPlayer();audio.stop();setTimeout(() => {this.duration = 0;}, 500);},// 播放async play(id: number) {console.log('play')if (id == this.id) return;this.ended = false;this.isPause = false;this.isPlaying = false;const data = await getSongUrl(id);console.log(data)// 篩掉會員歌曲和無版權(quán)歌曲 freeTrialInfo字段為試聽時間if(data.url && <img src="https://music.163.com/song/media/outer/url?id=' + data.id + '.mp3';// console.log(audio.title)audio.play();this.isPlaying = true;this.songUrl = data;this.url = data.url;audio.onError((err:any) => {this.id = id;uni.showToast({icon: "error",title: "該歌曲無法播放"})this.isPause = true;// this.deleteSong(id);// this.next();})}, 500)}else{uni.showToast({icon: "error",title: "該歌曲無法播放"})this.deleteSong(id);this.next();}},// 獲取歌詞async getLyric(id: number) {const lyricData = await getSongLyric(id);const lyric = JSON.parse(JSON.stringify(lyricData)).lyric;return lyric},// 緩存歌詞saveLyric(currentLyric: any) {this.currentLyric = currentLyric;},// 播放結(jié)束playEnd() {this.isPause = true;console.log('播放結(jié)束');switch (this.loopType) {case 0:this.next();break;case 1:this.rePlay();break;case 2:this.randomPlay();break;}},// 獲取歌曲詳情async songDetail() {this.song = await getSongDetail(this.id);this.pushPlayList(false, this.song);},// 重新播放rePlay() {setTimeout(() => {console.log('replay');this.currentTime = 0;this.ended = false;this.isPause = false;this.isPlaying = true;const audio = getPlayer();audio.seek(0);audio.play();}, 1500)},// 下一曲next() {if (this.loopType === 2) {this.randomPlay();} else {if(this.id === this.nextSong.id) {uni.showToast({icon: "none",title: "沒有下一首"})}else{this.play(this.nextSong.id);}}},// 上一曲prev() {if(this.id === this.prevSong.id) {uni.showToast({icon: "none",title: "沒有上一首"})}else{this.play(this.prevSong.id);}},// 隨機播放randomPlay() {console.log('randomPlay')this.play(this.playList[Math.ceil(Math.random() * this.playList.length - 1)].id,)},// 播放、暫停togglePlay() {if (!this.song.id) return;this.isPlaying = !this.isPlaying;const audio = getPlayer();if (!this.isPlaying) {audio.pause();this.isPause = true;} else {audio.play();this.isPause = false;}},setPlay() {if (!this.song.id) return;const audio = getPlayer();this.isPlaying = true;audio.play();this.isPause = false;},setPause() {if (!this.song.id) return;const audio = getPlayer();this.isPlaying = false;audio.pause();this.isPause = true;},// 切換循環(huán)類型toggleLoop() {if (this.loopType == 2) {this.loopType = 0;} else {this.loopType++;}},// 快進forward(val: number) {const audio = getPlayer();audio.seek(this.currentTime + val);},// 后退backup(val: number) {const audio = getPlayer();if(this.currentTime < 5) {audio.seek(0)}else{audio.seek(this.currentTime - val);}},// 修改播放時間onSliderChange(val: number) {const audio = getPlayer();audio.seek(val);},// 定時器interval() {if (this.isPlaying && !this.sliderInput) {const audio = getPlayer();this.currentTime = parseInt(audio.currentTime.toString());this.duration = parseInt(audio.duration.toString());audio.onEnded(() => {// console.log('end')this.ended = true})}},// 控制播放器顯隱setPlayerShow(val: number) {// val 0:顯示 1:隱藏if (val === 0) {this.playerShow = true;} else {this.playerShow = false;}}" style="margin: auto" />
})
export const useInitPlayer = () => {let timer: any;const { interval, playEnd, setPlayerShow } = usePlayerStore();const { ended, song } = storeToRefs(usePlayerStore());// 監(jiān)聽播放結(jié)束watch(ended, (ended) => {console.log('start')if (!ended) returnconsole.log('end')playEnd()}),// 監(jiān)聽當(dāng)前歌曲控制播放器顯隱watch(song, (song) => {if (song) {setPlayerShow(0);} else {setPlayerShow(1);}}),// 啟動定時器console.log('啟動定時器');timer = setInterval(interval, 1000);// 清除定時器onUnmounted(() => {console.log('清除定時器');clearInterval(timer);})
}
在App.vue
中創(chuàng)建Audio實例
并初始化播放器
// App.vue
import { onLaunch, onShow, onHide } from '@dcloudio/uni-app'
import { createPlayer } from '@/config/utils/initPlayer'
import { useInitPlayer } from '@/store/player'
onLaunch(() => {createPlayer()useInitPlayer() // 初始化播放器控件
})
現(xiàn)在全局播放器已經(jīng)初始化完成?
播放/暫停/切換/快進快退
由于已經(jīng)通過Pinia
封裝了播放器的基本功能,現(xiàn)在直接調(diào)用即可??
// song.vue
<!-- 播放器控制區(qū)域 -->
<view class="flex w-full justify-around items-center my-4"><!-- 上一首 --><i class="iconfont icon-shangyishoushangyige text-2xl" @click="prev"></i><!-- 快退 --><i class="iconfont icon-kuaitui text-3xl" @click="backup(5)"></i><!-- 播放/暫停 --><view><i v-if="!isPause" class="iconfont icon-zanting text-4xl" @click="togglePlay"></i><i v-else class="iconfont icon-bofang text-4xl" @click="togglePlay"></i></view><!-- 快進 --><i class="iconfont icon-kuaijin text-3xl" @click="forward(5)"></i><!-- 下一首 --><i class="iconfont icon-xiayigexiayishou text-2xl" @click="next"></i>
</view>
import { toRefs } from 'vue';
import { usePlayerStore } from '@/store/player';
const { song, id, isPause, togglePlay, forward, backup, next, prev } = toRefs(usePlayerStore());
實現(xiàn)聲波進度條??
一些音樂APP有時會使用聲波形狀的進度條,但在前端項目中很少看到有人使用??
此處進度條組件為了美觀方便采用固定聲波條數(shù)+固定樣式,可以根據(jù)實際需求對該組件進行改進
// MusicProgressBar.vue
<view class="w-full mt-4"><!-- skeleton --><view v-if="!duration" style="height: 62rpx" class="animate-pulse bg-gray-200"></view><!-- progressBar --><view v-else class="flex justify-center items-center"><view class="mr-4">{{ moment(currentTime * 1000).format('mm:ss') }}</view><view class="flex flex-shrink-0 justify-center items-center"><view v-for="(item) in 34" :key="item" class="progress-item":class="[currentLine < item ? 'line-' + (item) + '' : 'line-' + (item) + ' line_active' ]"@click="moveProgress(item)"></view></view><view class="ml-4">{{ moment(duration * 1000).format('mm:ss') }}</view></view>
</view>
import { toRefs, computed, getCurrentInstance } from 'vue';
import { usePlayerStore } from '@/store/player';
const { currentTime, duration } = toRefs(usePlayerStore());
const { onSliderChange } = usePlayerStore();
const moment = getCurrentInstance()?.appContext.config.globalProperties.$moment;
const currentLine = computed(() => {// 實時監(jiān)聽當(dāng)前進度條位置const val = duration.value / 34;// 獲取進度條單位長度const nowLine = (currentTime.value / val)return nowLine
})
const moveProgress = (index: number) => { // 拖動進度條改變歌曲播放進度// 小程序端拖拽時存在一定延遲const val = duration.value / 34;const newTime = Number((val * index).toFixed(0))onSliderChange(newTime)
}
.progress-item {width: 8rpx;margin: 2rpx;@apply bg-slate-300;
}
.line_active {@apply bg-blue-400
}
.line-1 {height: 12rpx;
}
.line-2 {height: 16rpx;
}
...
.line-34 {height: 12rpx;
}
實現(xiàn)效果??
那么到此為止,播放器的控制區(qū)域
就已經(jīng)全部實現(xiàn)了??????
歌詞解析
下面開始實現(xiàn)歌詞部分,首先處理接口返回的歌詞數(shù)據(jù): 網(wǎng)易云音樂接口文檔
[00:00.000] 作詞 : 太一\n[00:01.000] 作曲 : 太一\n[00:02.000] 編曲 : 太一\n[00:03.000] 制作人 : 太一\n[00:04.858]我決定撇棄我的回憶\n[00:08.126]摸了摸人類盛典的樣子\n[00:11.156]在此之前\n[00:12.857]我曾經(jīng)\n[00:14.377]善\n[00:15.076]意\n[00:15.932]過\n[00:16.760]\n[00:29.596]怎么懂\n[00:31.833]我該怎么能讓人懂\n[00:35.007]我只會跟耳朵相擁\n[00:38.226]天胡也救不了人的凡\n[00:41.512]涌遠(yuǎn)流動\n[00:44.321]神的眼睛該有擦鏡布\n[00:47.587]殘疾的心靈也很辛苦\n[00:50.755]真正摔過的流星乃真無數(shù)\n[00:56.002]\n[01:02.545]這一路磕磕絆絆走的倉促\n[01:05.135]爬上逆鱗摘下龍嘴里面含的珠\n[01:08.403]\n[01:08.781]“?.”\n[01:34.409]\n[01:37.920]只會用這樣的回答洗禮我內(nèi)心的不甘\n[01:40.571]因為皎潔的事情需要挖肺掏心的呼喊\n[01:43.367]人們總是仰頭看\n[01:44.510]總會莫名的忌憚\n[01:45.811]生怕觸動自己的不堪\n[01:47.402]壓低帽檐送世界一句\n[01:48.705]生\n[01:49.179]而\n[01:49.611]爛\n[01:50.012]漫\n[01:50.787]年輕人憑什么出頭誰啊誰啊非起竿\n[01:53.971]貼上個標(biāo)簽接受才比較比較簡單\n[01:57.210]沒有人會這樣描繪描繪音樂的圖案\n[02:00.168]他要是不死難道胸口畫了剜\n[02:03.218]\n[02:17.550]怎樣算漂亮\n[02:20.746]不想再仰望\n[02:23.943]這個梨不讓\n[02:28.126]這才是\n[02:28.791]我模樣\n[02:30.399]月泛光\n[02:31.976]赤裸胸膛還有跌宕\n[02:35.174]現(xiàn)實催促激素般的生長\n[02:38.363]心跳在消亡\n[02:39.960]脈搏在癲狂\n[02:41.588]我模樣\n[02:43.177]月泛光\n[02:44.752]踉蹌也要大旗飄揚\n[02:47.951]詩意都變的似笑非笑的堂皇\n[02:49.818]譜寫的變始料未料的蒼茫\n[02:51.368]人生沒下一場\n[02:52.583]可我不活那下一趟\n[03:01.452]\n[03:05.568]“?.”\n[03:31.195]\n[03:31.516] 和聲 : 太一\n[03:31.837] 器樂 : 太一\n[03:32.158] 錄音 : 太一\n[03:32.479] 混音 : 太一\n[03:32.800] 母帶 : 太一\n

接口返回的lyric
數(shù)據(jù)為string
類型,顯然是不能直接使用的,需要我們手動轉(zhuǎn)化成數(shù)組
形式
/**
*lyric2Array.ts
*將接口返回的lyric數(shù)據(jù)轉(zhuǎn)化成數(shù)組格式
*/
export interface ILyric {time: number,lyric: string,uid: number
}
interface IReturnLyric {lyric: ILyric[],// 歌詞tlyric?: ILyric[] // 翻譯歌詞
}
export const formatMusicLyrics = (lyric?: string, tlyric?: string):IReturnLyric => {if (lyric === '') {return { lyric: [{ time: 0, lyric: '暫無歌詞', uid: 520520 }] }}const lyricObjArr: ILyric[] = [] // 最終返回的歌詞數(shù)組// 將歌曲字符串變成數(shù)組,數(shù)組每一項就是當(dāng)前歌詞信息const lineLyric:any = lyric?.split(/\n/)// 匹配中括號里正則的const regTime = /\d{2}:\d{2}.\d{2,3}/// 循環(huán)遍歷歌曲數(shù)組for (let i = 0; i < lineLyric?.length; i++) {if (lineLyric[i] === '') continueconst time:number = formatLyricTime(lineLyric[i].match(regTime)[0])if (lineLyric[i].split(']')[1] !== '') {lyricObjArr.push({time: time,lyric: lineLyric[i].split(']')[1],uid: parseInt(Math.random().toString().slice(-6)) // 生成隨機uid})}}console.log(lyricObjArr)return {lyric: lyricObjArr}}const formatLyricTime = (time: string) => { // 格式化時間const regMin = /.*:/const regSec = /:.*\./const regMs = /\./const min = parseInt((time.match(regMin) as any)[0].slice(0, 2))let sec = parseInt((time.match(regSec) as any)[0].slice(1, 3))const ms = time.slice((time.match(regMs) as any).index + 1, (time.match(regMs) as any).index + 3)if (min !== 0) {sec += min * 60}return Number(sec + '.' + ms)
}
// song.vue
import { formatMusicLyrics } from '@/config/utils/lyric2Array';
const lyricData = ref<any>([]);
watch(() => id.value, (newVal, oldVal) => { // 歌曲歌詞同步切換console.log(newVal, oldVal)if(newVal !== oldVal) {nextTick(() => {getLyric(newVal).then((res) => {lyricData.value = formatMusicLyrics(res)})})}
})
getLyric(id.value).then((res) => {// 獲取歌詞lyricData.value = formatMusicLyrics(res)
})
轉(zhuǎn)換完成后的Lyric數(shù)據(jù):
歌詞滾動
有了數(shù)據(jù)后就可以對數(shù)據(jù)進行處理了??新建一個Lyric組件
處理歌詞滾動
和歌詞跳轉(zhuǎn)
的相關(guān)代碼,動態(tài)獲取組件高度
<Lyric :scrollHeight="scrollH" :lyricData="lyricData" />
<scroll-view id="lyric" scroll-y :scroll-top="scrollH" :style="{ 'height': scrollHeight + 'px'}"><view v-for="(item, index) in lyricData.lyric" :key="index"class="flex justify-center mx-8 text-center py-2 lyric-item":class="lyricIndex === index ? 'text-blue-300 opacity-100 scale-110' : 'opacity-20'"@click="lyricJump(index)">{{item.lyric}}</view>
</scroll-view>
import { ref, toRefs, watch, nextTick, getCurrentInstance } from 'vue';
import { usePlayerStore } from '@/store/player'
const { currentTime, id } = toRefs(usePlayerStore())
const { onSliderChange } = usePlayerStore();
...
const loading = ref<boolean>(true)
const lyricIndex = ref<number>(0) // 當(dāng)前高亮歌詞索引
let scrollH = ref<number>(0) // 歌詞居中顯示需要滾動的高度
let lyricH: number = 0 // 歌詞當(dāng)前的滾動高度
let flag: boolean = true // 判斷當(dāng)前高亮索引是否已經(jīng)超過了歌詞數(shù)組的長度
const currentInstance = getCurrentInstance(); // vue3綁定this
uni-app 微信小程序 通過
uni.createSelectorQuery()
獲取節(jié)點>H5端
和小程序端
歌詞滾動存在速度差
,暫時沒找到原因,需要對當(dāng)前歌詞高亮索引
進行條件編譯
// 核心方法 handleLyricTransform 計算當(dāng)前歌詞滾動高度實現(xiàn)高亮歌詞居中顯示
const handleLyricTransform = (currentTime: number) => { // 實現(xiàn)歌詞同步滾動nextTick(() => {// 獲取所有l(wèi)yric-item的節(jié)點數(shù)組loading.value = falseconst curIdx = props.lyricData.lyric.findIndex((item:any) => {// 獲取當(dāng)前索引return (currentTime <= item.time)})// const item = props.lyricData.lyric[curIdx - 1] // 獲取當(dāng)前歌詞信息// 獲取lyric節(jié)點const LyricRef = uni.createSelectorQuery().in(currentInstance).select("#lyric");LyricRef.boundingClientRect((res) => {if(res) {// 獲取lyric高度的1/2,用于實現(xiàn)自動居中定位const midLyricViewH = ((res as any).height / 2)if(flag) {// 實時獲取最新Domconst lyricRef = uni.createSelectorQuery().in(currentInstance).selectAll(".lyric-item");lyricRef.boundingClientRect((res) => {if(res) {// console.log(res)// 獲取當(dāng)前播放歌詞對應(yīng)索引 H5端 curIdx - 1 | 微信小程序端 curIdx// #ifdef MP-WEIXINlyricIndex.value = curIdx;// 獲得高亮索引// #endif// #ifndef MP-WEIXINlyricIndex.value = curIdx - 1;// 獲得高亮索引// #endifif (lyricIndex.value >= (res as Array<any>).length) {flag = falsereturn}lyricH = ((res as Array<any>)[curIdx].top - (res as Array<any>)[0].top)if(midLyricViewH > 0 && lyricH > midLyricViewH) {scrollH.value = lyricH - midLyricViewH}}}).exec()}}}).exec()})
}
這里的重點主要是handleLyricTransform
的調(diào)用時機,由于需要根據(jù)歌曲播放進度實時改變,因此需要監(jiān)聽currentTime
變化
// 監(jiān)聽歌曲播放進程
watch(() => currentTime.value, (val) => {// console.log(val)handleLyricTransform(val)
})

歌詞跳轉(zhuǎn)
最后實現(xiàn)歌詞跳轉(zhuǎn),通過lyricJump
方法調(diào)用usePlayerStore的onSliderChange
const lyricJump = (index: number) => {onSliderChange(Number(props.lyricData.lyric[index].time.toFixed(0)))lyricIndex.value = index
}

最后進行一些邊界處理,刷新頁面防止播放數(shù)據(jù)異常直接返回首頁
,切換歌曲重置歌詞狀態(tài)
,添加切換動畫
等等…
最后
整理了一套《前端大廠面試寶典》,包含了HTML、CSS、JavaScript、HTTP、TCP協(xié)議、瀏覽器、VUE、React、數(shù)據(jù)結(jié)構(gòu)和算法,一共201道面試題,并對每個問題作出了回答和解析。
有需要的小伙伴,可以點擊文末卡片領(lǐng)取這份文檔,無償分享
部分文檔展示:
文章篇幅有限,后面的內(nèi)容就不一一展示了文章來源:http://www.zghlxwxcb.cn/news/detail-820546.html
有需要的小伙伴,可以點下方卡片免費領(lǐng)取文章來源地址http://www.zghlxwxcb.cn/news/detail-820546.html
到了這里,關(guān)于uni-app Vue3實現(xiàn)一個酷炫的多功能音樂播放器支持微信小程序后臺播放的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!