欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于Vue3編寫一個(gè)簡(jiǎn)單的播放器

 更新時(shí)間:2023年03月02日 11:07:18   作者:65歲退休Coder  
這篇文章主要為大家詳細(xì)介紹了如何基于Vue3編寫一個(gè)簡(jiǎn)單的播放器,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Vue3有一定的幫助,需要的可以參考一下

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)

timeupdatecurrentTime 變更時(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)文章

最新評(píng)論