基于Vue3編寫一個(gè)簡(jiǎn)單的播放器
TODO
- 實(shí)現(xiàn)播放/暫停;
- 實(shí)現(xiàn)開(kāi)始/結(jié)束時(shí)間及開(kāi)始時(shí)間和滾動(dòng)條動(dòng)態(tài)跟隨播放動(dòng)態(tài)變化;
- 實(shí)現(xiàn)點(diǎn)擊進(jìn)度條跳轉(zhuǎn)指定播放位置;
- 實(shí)現(xiàn)點(diǎn)擊圓點(diǎn)拖拽滾動(dòng)條。
頁(yè)面布局及 css
樣式如下
<template> <div class="song-item"> <audio src="" /> <!-- 進(jìn)度條 --> <div class="audio-player"> <span>00:00</span> <div class="progress-wrapper"> <div class="progress-inner"> <div class="progress-dot" /> </div> </div> <span>00:00</span> <!-- 播放/暫停 --> <div style="margin-left: 10px; color: #409eff; cursor: pointer;" > 播放 </div> </div> </div> </template> <style lang="scss"> * { font-size: 14px; } .song-item { display: flex; flex-direction: column; justify-content: center; height: 100px; padding: 0 20px; transition: all ease .2s; border-bottom: 1px solid #ddd; /* 進(jìn)度條樣式 */ .audio-player { display: flex; height: 18px; margin-top: 10px; align-items: center; font-size: 12px; color: #666; .progress-wrapper { flex: 1; height: 4px; margin: 0 20px 0 20px; border-radius: 2px; background-color: #e9e9eb; cursor: pointer; .progress-inner { position: relative; width: 0%; height: 100%; border-radius: 2px; background-color: #409eff; .progress-dot { position: absolute; top: 50%; right: 0; z-index: 1; width: 10px; height: 10px; border-radius: 50%; background-color: #409eff; transform: translateY(-50%); } } } } } </style>
實(shí)現(xiàn)播放/暫停
思路:給 ”播放“ 注冊(cè)點(diǎn)擊事件,在點(diǎn)擊事件中通過(guò) audio
的屬性及方法來(lái)判定當(dāng)前歌曲是什么狀態(tài),是否播放或暫停,然后聲明一個(gè)屬性同步這個(gè)狀態(tài),在模板中做出判斷當(dāng)前應(yīng)該顯示 ”播放/暫停“。
關(guān)鍵性 api:
audio.paused
:當(dāng)前播放器是否為暫停狀態(tài)
audio.play()
:播放
audio.pause()
:暫停
const audioIsPlaying = ref(false); // 用于同步當(dāng)前的播放狀態(tài) const audioEle = ref<HTMLAudioElement | null>(null); // audio 元素 /** * @description 播放/暫停音樂(lè) */ const togglePlayer = () => { if (audioEle.value) { if (audioEle.value?.paused) { audioEle.value.play(); audioIsPlaying.value = true; } else { audioEle.value?.pause(); audioIsPlaying.value = false; } } }; onMounted(() => { // 頁(yè)面點(diǎn)擊的時(shí)候肯定是加載完成了,這里獲取一下沒(méi)毛病 audioEle.value = document.querySelector('audio'); });
最后把屬性及事件應(yīng)用到模板中去。
<div style="margin-left: 10px; color: #409eff; cursor: pointer;" @click="togglePlayer" > {{ audioIsPlaying ? '暫停' : '播放'}} </div>
實(shí)現(xiàn)開(kāi)始/結(jié)束時(shí)間及開(kāi)始時(shí)間和滾動(dòng)條動(dòng)態(tài)跟隨播放動(dòng)態(tài)變化
思路:獲取當(dāng)前已經(jīng)播放的時(shí)間及總時(shí)長(zhǎng),然后再拿當(dāng)前時(shí)長(zhǎng) / 總時(shí)長(zhǎng)及得到歌曲播放的百分比即滾動(dòng)條的百分比。通過(guò)偵聽(tīng) audio
元素的 timeupdate
事件以做到每次當(dāng)前時(shí)間改變時(shí),同步把 DOM 也進(jìn)行更新。最后播放完成后把狀態(tài)初始化。
關(guān)鍵性api:
audio.currentTime
:當(dāng)前的播放時(shí)間;單位(s)
audio.duration
:音頻的總時(shí)長(zhǎng);單位(s)
timeupdate
:currentTime
變更時(shí)會(huì)觸發(fā)該事件。
import dayjs from 'dayjs'; const audioCurrentPlayTime = ref('00:00'); // 當(dāng)前播放時(shí)長(zhǎng) const audioCurrentPlayCountTime = ref('00:00'); // 總時(shí)長(zhǎng) const pgsInnerEle = ref<HTMLDivElement | null>(null); /** * @description 更新進(jìn)度條與當(dāng)前播放時(shí)間 */ const updateProgress = () => { const currentProgress = audioEle.value!.currentTime / audioEle.value!.duration; pgsInnerEle.value!.style.width = `${currentProgress * 100}%`; // 設(shè)置進(jìn)度時(shí)長(zhǎng) if (audioEle.value) audioCurrentPlayTime.value = dayjs(audioEle.value.currentTime * 1000).format('mm:ss'); }; /** * @description 播放完成重置播放狀態(tài) */ const audioPlayEnded = () => { audioCurrentPlayTime.value = '00:00'; pgsInnerEle.value!.style.width = '0%'; audioIsPlaying.value = false; }; onMounted(() => { pgsInnerEle.value = document.querySelector('.progress-inner'); // 設(shè)置總時(shí)長(zhǎng) if (audioEle.value) audioCurrentPlayCountTime.value = dayjs(audioEle.value.duration * 1000).format('mm:ss'); // 偵聽(tīng)播放中事件 audioEle.value?.addEventListener('timeupdate', updateProgress, false); // 播放結(jié)束 event audioEle.value?.addEventListener('ended', audioPlayEnded, false); });
實(shí)現(xiàn)點(diǎn)擊進(jìn)度條跳轉(zhuǎn)指定播放位置
思路:給滾動(dòng)條注冊(cè)鼠標(biāo)點(diǎn)擊事件,每次點(diǎn)擊的時(shí)候獲取當(dāng)前的 offsetX
以及滾動(dòng)條的寬度,用寬度 / offsetX
最后用總時(shí)長(zhǎng) * 前面的商就得到了我們想要的進(jìn)度,再次更新進(jìn)度條即可。
關(guān)鍵性api:
event.offsetX
:鼠標(biāo)指針相較于觸發(fā)事件對(duì)象的 x 坐標(biāo)。
/** * @description 點(diǎn)擊滾動(dòng)條同步更新音樂(lè)進(jìn)度 */ const clickProgressSync = (event: MouseEvent) => { if (audioEle.value) { // 保證是正在播放或者已經(jīng)播放的狀態(tài) if (!audioEle.value.paused || audioEle.value.currentTime !== 0) { const pgsWrapperWidth = pgsWrapperEle.value!.getBoundingClientRect().width; const rate = event.offsetX / pgsWrapperWidth; // 同步滾動(dòng)條和播放進(jìn)度 audioEle.value.currentTime = audioEle.value.duration * rate; updateProgress(); } } }; onMounted({ pgsWrapperEle.value = document.querySelector('.progress-wrapper'); // 點(diǎn)擊進(jìn)度條 event pgsWrapperEle.value?.addEventListener('mousedown', clickProgressSync, false); }); // 別忘記統(tǒng)一移除偵聽(tīng) onBeforeUnmount(() => { audioEle.value?.removeEventListener('timeupdate', updateProgress); audioEle.value?.removeEventListener('ended', audioPlayEnded); pgsWrapperEle.value?.removeEventListener('mousedown', clickProgressSync); });
實(shí)現(xiàn)點(diǎn)擊圓點(diǎn)拖拽滾動(dòng)條
思路:使用 hook
管理這個(gè)拖動(dòng)的功能,偵聽(tīng)這個(gè)滾動(dòng)條的 鼠標(biāo)點(diǎn)擊、鼠標(biāo)移動(dòng)、鼠標(biāo)抬起事件。
點(diǎn)擊時(shí): 獲取鼠標(biāo)在窗口的 x
坐標(biāo),圓點(diǎn)距離窗口的 left
距離及最大的右移距離(滾動(dòng)條寬度 - 圓點(diǎn)距離窗口的 left
)。為了讓移動(dòng)式不隨便開(kāi)始計(jì)算,在開(kāi)始的時(shí)候可以弄一個(gè)開(kāi)關(guān) flag
移動(dòng)時(shí): 實(shí)時(shí)獲取鼠標(biāo)在窗口的 x
坐標(biāo)減去 點(diǎn)擊時(shí)獲取的 x
坐標(biāo)。然后根據(jù)最大移動(dòng)距離做出判斷,不要讓它越界。最后: 總時(shí)長(zhǎng) * (圓點(diǎn)距離窗口的 left
+ 計(jì)算得出的 x
/ 滾動(dòng)條長(zhǎng)度) 得出百分比更新滾動(dòng)條及進(jìn)度
抬起時(shí):將 flag
重置。
/** * @method useSongProgressDrag * @param audioEle * @param pgsWrapperEle * @param updateProgress 更新滾動(dòng)條方法 * @param startSongDragDot 是否開(kāi)啟拖拽滾動(dòng) * @description 拖拽更新歌曲播放進(jìn)度 */ const useSongProgressDrag = ( audioEle: Ref<HTMLAudioElement | null>, pgsWrapperEle: Ref<HTMLDivElement | null>, updateProgress: () => void, startSongDragDot: Ref<boolean> ) => { const audioPlayer = ref<HTMLDivElement | null>(null); const audioDotEle = ref<HTMLDivElement | null>(null); const dragFlag = ref(false); const position = ref({ startOffsetLeft: 0, startX: 0, maxLeft: 0, maxRight: 0, }); /** * @description 鼠標(biāo)點(diǎn)擊 audioPlayer */ const mousedownProgressHandle = (event: MouseEvent) => { if (audioEle.value) { if (!audioEle.value.paused || audioEle.value.currentTime !== 0) { dragFlag.value = true; position.value.startOffsetLeft = audioDotEle.value!.offsetLeft; position.value.startX = event.clientX; position.value.maxLeft = position.value.startOffsetLeft; position.value.maxRight = pgsWrapperEle.value!.offsetWidth - position.value.startOffsetLeft; } } event.preventDefault(); event.stopPropagation(); }; /** * @description 鼠標(biāo)移動(dòng) audioPlayer */ const mousemoveProgressHandle = (event: MouseEvent) => { if (dragFlag.value) { const clientX = event.clientX; let x = clientX - position.value.startX; if (x > position.value.maxRight) x = position.value.maxRight; if (x < -position.value.maxLeft) x = -position.value.maxLeft; const pgsWidth = pgsWrapperEle.value?.getBoundingClientRect().width; const reat = (position.value.startOffsetLeft + x) / pgsWidth!; audioEle.value!.currentTime = audioEle.value!.duration * reat; updateProgress(); } }; /** * @description 鼠標(biāo)取消點(diǎn)擊 */ const mouseupProgressHandle = () => dragFlag.value = false; onMounted(() => { if (startSongDragDot.value) { audioPlayer.value = document.querySelector('.audio-player'); audioDotEle.value = document.querySelector('.progress-dot'); // 在捕獲中去觸發(fā)點(diǎn)擊 dot 事件. fix: 點(diǎn)擊原點(diǎn) offset 回到原點(diǎn) bug audioDotEle.value?.addEventListener('mousedown', mousedownProgressHandle, true); audioPlayer.value?.addEventListener('mousemove', mousemoveProgressHandle, false); document.addEventListener('mouseup', mouseupProgressHandle, false); } }); onBeforeUnmount(() => { if (startSongDragDot.value) { audioPlayer.value?.removeEventListener('mousedown', mousedownProgressHandle); audioPlayer.value?.removeEventListener('mousemove', mousemoveProgressHandle); document.removeEventListener('mouseup', mouseupProgressHandle); } }); };
最后調(diào)用這個(gè) hook
// 是否顯示可拖拽 dot // 可以在原點(diǎn)元素上增加 v-if 用來(lái)判定是否需要拖動(dòng)功能 const startSongDragDot = ref(true); useSongProgressDrag(audioEle, pgsWrapperEle, updateProgress, startSongDragDot);
以上就是基于Vue3編寫一個(gè)簡(jiǎn)單的播放器的詳細(xì)內(nèi)容,更多關(guān)于Vue3播放器的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
詳解vue數(shù)據(jù)渲染出現(xiàn)閃爍問(wèn)題
本篇文章主要介紹了vue數(shù)據(jù)渲染出現(xiàn)閃爍問(wèn)題,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-06-06解決vuex數(shù)據(jù)異步造成初始化的時(shí)候沒(méi)值報(bào)錯(cuò)問(wèn)題
今天小編大家分享一篇解決vuex數(shù)據(jù)異步造成初始化的時(shí)候沒(méi)值報(bào)錯(cuò)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11Vue2.0實(shí)現(xiàn)1.0的搜索過(guò)濾器功能實(shí)例代碼
本篇文章主要介紹了Vue2.0實(shí)現(xiàn)1.0的搜索過(guò)濾器功能實(shí)例代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-03-03Vue 中頁(yè)面?zhèn)髦档亩喾N方式小結(jié)
本文主要介紹了Vue 中頁(yè)面?zhèn)髦档亩喾N方式小結(jié),主要包括路由傳參、Vuex 狀態(tài)管理、Props 屬性和事件傳遞數(shù)據(jù)這幾種,具有一定的參考價(jià)值,感興趣的可以了解一下2023-10-10Vue.js實(shí)戰(zhàn)之使用Vuex + axios發(fā)送請(qǐng)求詳解
這篇文章主要給大家介紹了關(guān)于Vue.js使用Vuex與axios發(fā)送請(qǐng)求的相關(guān)資料,文中介紹的非常詳細(xì),相信對(duì)大家具有一定的參考價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-04-04vue?el-switch初始值(默認(rèn)值)不能正確顯示狀態(tài)問(wèn)題及解決
這篇文章主要介紹了vue?el-switch初始值(默認(rèn)值)不能正確顯示狀態(tài)問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10vue 實(shí)現(xiàn)input表單元素的disabled示例
今天小編就為大家分享一篇vue 實(shí)現(xiàn)input表單元素的disabled示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-10-10vue實(shí)現(xiàn)標(biāo)簽頁(yè)切換/制作tab組件詳細(xì)教程
在項(xiàng)目開(kāi)發(fā)中需要使用vue實(shí)現(xiàn)tab頁(yè)簽切換功能,所以這里總結(jié)下,這篇文章主要給大家介紹了關(guān)于vue實(shí)現(xiàn)標(biāo)簽頁(yè)切換/制作tab組件的相關(guān)資料,需要的朋友可以參考下2023-11-11詳解vuex中action何時(shí)完成以及如何正確調(diào)用dispatch的思考
這篇文章主要介紹了詳解vuex中action何時(shí)完成以及如何正確調(diào)用dispatch的思考,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-01-01