溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何用Vue3寫播放器

發(fā)布時間:2023-03-06 09:23:11 來源:億速云 閱讀:105 作者:iii 欄目:編程語言

今天小編給大家分享一下如何用Vue3寫播放器的相關(guān)知識點,內(nèi)容詳細,邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。

TODO

  • 實現(xiàn)播放/暫停;

  • 實現(xiàn)開始/結(jié)束時間及開始時間和滾動條動態(tài)跟隨播放動態(tài)變化;

  • 實現(xiàn)點擊進度條跳轉(zhuǎn)指定播放位置;

  • 實現(xiàn)點擊圓點拖拽滾動條。

頁面布局及 css 樣式如下

<template>
 <div class="song-item">
   <audio src="" />
   <!-- 進度條 -->
   <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;    /* 進度條樣式 */
   .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>

實現(xiàn)播放/暫停

思路:給 ”播放“ 注冊點擊事件,在點擊事件中通過 audio 的屬性及方法來判定當前歌曲是什么狀態(tài),是否播放或暫停,然后聲明一個屬性同步這個狀態(tài),在模板中做出判斷當前應(yīng)該顯示 ”播放/暫?!啊?/p>

關(guān)鍵性 api:

audio.paused:當前播放器是否為暫停狀態(tài)

audio.play():播放

audio.pause():暫停

const audioIsPlaying = ref(false); // 用于同步當前的播放狀態(tài)const audioEle = ref<HTMLAudioElement | null>(null); // audio 元素/**
* @description 播放/暫停音樂
*/const togglePlayer = () => {  if (audioEle.value) {    if (audioEle.value?.paused) {
     audioEle.value.play();
     audioIsPlaying.value = true;
   }    else {
     audioEle.value?.pause();
     audioIsPlaying.value = false;
   }
 }
};onMounted(() => {  // 頁面點擊的時候肯定是加載完成了,這里獲取一下沒毛病
 audioEle.value = document.querySelector('audio');
});

最后把屬性及事件應(yīng)用到模板中去。

<div 
 style="margin-left: 10px; color: #409eff; cursor: pointer;"
 @click="togglePlayer">
 {{ audioIsPlaying ? '暫停' : '播放'}}</div>

實現(xiàn)開始/結(jié)束時間及開始時間和滾動條動態(tài)跟隨播放動態(tài)變化

思路:獲取當前已經(jīng)播放的時間及總時長,然后再拿當前時長 / 總時長及得到歌曲播放的百分比即滾動條的百分比。通過偵聽 audio 元素的 timeupdate 事件以做到每次當前時間改變時,同步把 DOM 也進行更新。最后播放完成后把狀態(tài)初始化。

關(guān)鍵性api:

audio.currentTime:當前的播放時間;單位(s)

audio.duration:音頻的總時長;單位(s)

timeupdatecurrentTime 變更時會觸發(fā)該事件。

import dayjs from 'dayjs';const audioCurrentPlayTime = ref('00:00'); // 當前播放時長const audioCurrentPlayCountTime = ref('00:00'); // 總時長const pgsInnerEle = ref<HTMLDivElement | null>(null);/**
* @description 更新進度條與當前播放時間
*/const updateProgress = () => {  const currentProgress = audioEle.value!.currentTime / audioEle.value!.duration;

 pgsInnerEle.value!.style.width = `${currentProgress * 100}%`;  // 設(shè)置進度時長
 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è)置總時長
 if (audioEle.value)
   audioCurrentPlayCountTime.value = dayjs(audioEle.value.duration * 1000).format('mm:ss');    
 // 偵聽播放中事件
 audioEle.value?.addEventListener('timeupdate', updateProgress, false);  // 播放結(jié)束 event
 audioEle.value?.addEventListener('ended', audioPlayEnded, false);
});

實現(xiàn)點擊進度條跳轉(zhuǎn)指定播放位置

思路:給滾動條注冊鼠標點擊事件,每次點擊的時候獲取當前的 offsetX 以及滾動條的寬度,用寬度 / offsetX 最后用總時長 * 前面的商就得到了我們想要的進度,再次更新進度條即可。

關(guān)鍵性api:

event.offsetX:鼠標指針相較于觸發(fā)事件對象的 x 坐標。

/**
* @description 點擊滾動條同步更新音樂進度
*/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;      // 同步滾動條和播放進度
     audioEle.value.currentTime = audioEle.value.duration * rate;      updateProgress();
   }
 }
};onMounted({
 pgsWrapperEle.value = document.querySelector('.progress-wrapper');  // 點擊進度條 event
 pgsWrapperEle.value?.addEventListener('mousedown', clickProgressSync, false);
});// 別忘記統(tǒng)一移除偵聽onBeforeUnmount(() => {
 audioEle.value?.removeEventListener('timeupdate', updateProgress);
 audioEle.value?.removeEventListener('ended', audioPlayEnded);
 pgsWrapperEle.value?.removeEventListener('mousedown', clickProgressSync);
});

實現(xiàn)點擊圓點拖拽滾動條。

思路:使用 hook 管理這個拖動的功能,偵聽這個滾動條的 鼠標點擊、鼠標移動、鼠標抬起事件。

點擊時: 獲取鼠標在窗口的 x 坐標,圓點距離窗口的 left 距離及最大的右移距離(滾動條寬度 - 圓點距離窗口的 left)。為了讓移動式不隨便開始計算,在開始的時候可以弄一個開關(guān) flag

移動時: 實時獲取鼠標在窗口的 x 坐標減去 點擊時獲取的 x 坐標。然后根據(jù)最大移動距離做出判斷,不要讓它越界。最后: 總時長 * (圓點距離窗口的 left + 計算得出的 x / 滾動條長度) 得出百分比更新滾動條及進度

抬起時:將 flag 重置。

/**
* @method useSongProgressDrag
* @param audioEle
* @param pgsWrapperEle
* @param updateProgress 更新滾動條方法
* @param startSongDragDot 是否開啟拖拽滾動
* @description 拖拽更新歌曲播放進度
*/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 鼠標點擊 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 鼠標移動 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 鼠標取消點擊
  */
 const mouseupProgressHandle = () => dragFlag.value = false;  onMounted(() => {    if (startSongDragDot.value) {
     audioPlayer.value = document.querySelector('.audio-player');
     audioDotEle.value = document.querySelector('.progress-dot');      // 在捕獲中去觸發(fā)點擊 dot 事件. fix: 點擊原點 offset 回到原點 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)用這個 hook

// 是否顯示可拖拽 dot// 可以在原點元素上增加 v-if 用來判定是否需要拖動功能const startSongDragDot = ref(true);useSongProgressDrag(audioEle, pgsWrapperEle, updateProgress, startSongDragDot);

以上就是“如何用Vue3寫播放器”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學習更多的知識,請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI