uni-app(vue)基於InnerAudioContext封裝一個基本的音頻組件

起因

一樣的是由於小程序官方不維護audio組件了javascript

音頻組件的要求與限制

  1. 點擊播放或者暫停
  2. 顯示播放進度及總時長
  3. 經過圖標變化顯示當前音頻所處狀態(暫停/播放/加載中)
  4. 頁面音頻更新時刷新組件狀態
  5. 全局有且只有一個音頻處於播放狀態
  6. 離開頁面以後要自動中止播放並銷燬音頻實例

材料/屬性/方法

讓咱們開始吧🛠css

uni-app Vue

  • 一樣的先構造DOM結構
<view class="custom-audio">
  <image v-if="audioSrc !== undefined && audioSrc !== null && audioSrc !== ''" @click="playOrStopAudio" :src="audioImg" class="audio-btn" />
  <text v-else @click="tips" class="audio-btn">無音源</text>
  <text>{{ fmtSecond(currentTime) }}/{{ fmtSecond(duration) }}</text>
</view>
  • 定義接受的組件
props: {
  audioSrc: {
    type: String,
    default: ''
  },
},
  • 定義CustomAudio組件的初始化相關的操做,並給innerAudioContext的回調添加一些行爲(以前Taro那篇咱們踩過的坑這裏就直接上代碼了)
import { formatSecondToHHmmss, afterAudioPlay, beforeAudioRecordOrPlay } from '../../lib/Utils'
const iconPaused = '../../static/images/icon_paused.png'
const iconPlaying = '../../static/images/icon_playing.png'
const iconStop = '../../static/images/icon_stop.png'
const iconLoading = '../../static/images/icon_loading.gif'
// ...
data() {
  return {
    audioCtx: null, // 音頻上下文
    duration: 0, // 音頻總時長
    currentTime: 0, // 音頻當前播放的時長
    audioImg: iconLoading, // 默認狀態爲加載中
  }
},
watch: {
  audioSrc: {
    handler(newSrc, oldSrc) {
      console.log('watch', newSrc, oldSrc)
      this.audioImg = iconLoading
      this.currentTime = 0
      this.duration = 0
      if (this.audioCtx === undefined) {
        this.audioCtx = uni.createInnerAudioContext()
        this.onTimeUpdate = this.audioCtx.onTimeUpdate
        this.bindAuidoCallback(this.audioCtx)
      } else {
        this.audioCtx.src = newSrc
      }
      if (this.audioCtx.play) {
        this.audioCtx.stop()
        getApp().globalData.audioPlaying = false
      }
    }
  }
},
mounted() {
  this.audioCtx = uni.createInnerAudioContext()
  this.audioCtx.src = this.audioSrc
  this.audioCtx.startTime = 0
  this.bindAuidoCallback(this.audioCtx)
},
methods: {
  bindAuidoCallback(ctx) {
    ctx.onTimeUpdate((e) => {
      this.onTimeUpdate(e)
    })
    ctx.onCanplay((e) => {
      this.onCanplay(e)
    })
    ctx.onWaiting((e) => {
      this.onWaiting(e)
    })
    ctx.onPlay((e) => {
      this.onPlay(e)
    })
    ctx.onPause((e) => {
      this.onPause(e)
    })
    ctx.onEnded((e) => {
      this.onEnded(e)
    })
    ctx.onError((e) => {
      this.onError(e)
    })
  },
  tips(){
    uni.showToast({
      title: '無效音源,請先錄音',
      icon: 'none'
    })
  },
  playOrStopAudio() {
    if (this.audioCtx === null) {
      this.audioCtx = uni.createInnerAudioContext()
      this.audioCtx.src = this.audioSrc
      this.bindAuidoCallback(this.audioCtx)
    }
    if (this.audioCtx.paused) {
      if (beforeAudioRecordOrPlay('play')) {
        this.audioCtx.play()
        this.audioImg = iconPlaying
      }
    } else {
      this.audioCtx.pause()
      afterAudioPlay()
      this.audioImg = iconPaused
    }
  },
  onTimeUpdate(e) {
    console.log('onTimeUpdate', this.audioCtx.duration, this.audioCtx.currentTime)
    if (this.audioCtx.currentTime > 0 && this.audioCtx.currentTime <= 1) {
      this.currentTime = 1
    } else if (this.currentTime !== Math.floor(this.audioCtx.currentTime)) {
      this.currentTime = Math.floor(this.audioCtx.currentTime)
    }
    const duration = Math.floor(this.audioCtx.duration)
    if (this.duration !== duration) {
      this.duration = duration
    }
  },
  onCanplay(e) {
    if (this.audioImg === iconLoading) {
      this.audioImg = iconPaused
    }
    console.log('onCanplay', e)
  },
  onWaiting(e) {
    if (this.audioImg !== iconLoading) {
      this.audioImg = iconLoading
    }
  },
  onPlay(e) {
    console.log('onPlay', e, this.audioCtx.duration)
    this.audioImg = iconPlaying
    if (this.audioCtx.duration > 0 && this.audioCtx.duration <= 1) {
      this.duration = 1
    } else {
      this.duration = Math.floor(this.audioCtx.duration)
    }
  },
  onPause(e) {
    console.log('onPause', e)
    this.audioImg = iconPaused
  },
  onEnded(e) {
    console.log('onEnded', e)
    if (this.audioImg !== iconPaused) {
      this.audioImg = iconPaused
    }
    afterAudioPlay()
  },
  onError(e) {
    uni.showToast({
      title: '音頻加載失敗',
      icon: 'none'
    })
    throw new Error(e.errMsg, e.errCode)
  },
  fmtSecond(sec) {
    const { min, second } = formatSecondToHHmmss(sec)
    return `${min}:${second}`
  }
},

一樣的scss文件

<style lang="scss" scoped>
.custom-audio {
  border-radius: 8vw;
  border: #CCC 1px solid;
  background: #F3F6FC;
  color: #333;
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
  justify-content: space-between;
  padding: 2vw;
  font-size: 14px;
  .audio-btn {
    width: 10vw;
    height: 10vw;
    white-space: nowrap;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>

最後

各位有遇到什麼問題或有什麼建議的能夠跟我討論喲~html

相關文章
相關標籤/搜索