1. 程式人生 > >音訊播放元件

音訊播放元件

<template>
  <div class="di main-wrap" v-loading="audio.waiting">
    <!-- 這裡設定了ref屬性後,在vue元件中,就可以用this.$refs.audio來訪問該dom元素 -->
    <audio ref="audio" class="dn" 
    :src="url" :preload="audio.preload"
    @play="onPlay" 
    @error="onError"
    @waiting="onWaiting"
    @pause="onPause" 
    @timeupdate="onTimeupdate" 
    @loadedmetadata="onLoadedmetadata"
    ></audio>
    <div>
      <el-button type="text" @click="startPlayOrPause">{{audio.playing | transPlayPause}}</el-button>
      <el-button v-show="!controlList.noSpeed" type="text" @click="changeSpeed">{{audio.speed | transSpeed}}</el-button>

      <el-tag type="info">{{ audio.currentTime | formatSecond}}</el-tag>

      <el-slider v-show="!controlList.noProcess" v-model="sliderTime" :format-tooltip="formatProcessToolTip" @change="changeCurrentTime" class="slider"></el-slider>
      
      <el-tag type="info">{{ audio.maxTime | formatSecond }}</el-tag>

      <el-button v-show="!controlList.noMuted" type="text" @click="startMutedOrNot">{{audio.muted | transMutedOrNot}}</el-button>

      <el-slider v-show="!controlList.noVolume" v-model="volume" :format-tooltip="formatVolumeToolTip" @change="changeVolume" class="slider"></el-slider>
      
    <el-button v-if="canDownload" type="primary" @click="downloadMusic">下載音樂</el-button>
    </div>
  </div>
</template>

<script>
  import saveAs from 'file-saver' // eslint-disable-line
  var FileSaver = require('file-saver')
  function realFormatSecond(second) {
    var secondType = typeof second
    if (secondType === 'number' || secondType === 'string') {
      second = parseInt(second)
      var hours = Math.floor(second / 3600)
      second = second - hours * 3600
      var mimute = Math.floor(second / 60)
      second = second - mimute * 60
      return hours + ':' + ('0' + mimute).slice(-2) + ':' + ('0' + second).slice(-2)
    } else {
      return '0:00:00'
    }
  }
  export default {
    props: {
      theUrl: {
        type: String,
        required: true,
      },
      theSpeeds: {
        type: Array,
        default () {
          return [1, 1.5, 2]
        }
      },
      theControlList: {
        type: String,
        default: ''
      }
    },
    name: 'VueAudio',
    data() {
      return {
        url: this.theUrl || 'http://devtest.qiniudn.com/secret base~.mp3',
        audio: {
          currentTime: 0,
          maxTime: 0,
          playing: false,
          muted: false,
          speed: 1,
          waiting: true,
          preload: 'auto'
        },
        sliderTime: 0,
        volume: 100,
        speeds: this.theSpeeds,
        controlList: {
          // 不顯示下載
          noDownload: false,
          // 不顯示靜音
          noMuted: false,
          // 不顯示音量條
          noVolume: false,
          // 不顯示進度條
          noProcess: false,
          // 只能播放一個
          onlyOnePlaying: false,
          // 不要快進按鈕
          noSpeed: false
        }
      }
    },
    methods: {
      setControlList () {
        let controlList = this.theControlList.split(' ')
        controlList.forEach((item) => {
          if(this.controlList[item] !== undefined){
            this.controlList[item] = true
          }
        })
      },
      changeSpeed() {
        let index = this.speeds.indexOf(this.audio.speed) + 1
        this.audio.speed = this.speeds[index % this.speeds.length]
        this.$refs.audio.playbackRate = this.audio.speed
      },
      startMutedOrNot() {
        this.$refs.audio.muted = !this.$refs.audio.muted
        this.audio.muted = this.$refs.audio.muted
      },
      // 音量條toolTip
      formatVolumeToolTip(index) {
        return '音量條: ' + index
      },
      // 進度條toolTip
      formatProcessToolTip(index = 0) {
        index = parseInt(this.audio.maxTime / 100 * index)
        return '進度條: ' + realFormatSecond(index)
      },
      // 音量改變
      changeVolume(index = 0) {
        this.$refs.audio.volume = index / 100
        this.volume = index
      },
      // 播放跳轉
      changeCurrentTime(index) {
        this.$refs.audio.currentTime = parseInt(index / 100 * this.audio.maxTime)
      },
      startPlayOrPause() {
        return this.audio.playing ? this.pausePlay() : this.startPlay()
      },
      // 開始播放
      startPlay() {
        this.$refs.audio.play()
      },
      // 暫停
      pausePlay() {
        this.$refs.audio.pause()
      },
      // 當音訊暫停
      onPause () {
        this.audio.playing = false
      },
      // 當發生錯誤, 就出現loading狀態
      onError () {
        this.audio.waiting = true
      },
      // 當音訊開始等待
      onWaiting (res) {
        console.log(res)
      },
      // 當音訊開始播放
      onPlay (res) {
        console.log(res)
        this.audio.playing = true
        this.audio.loading = false
        if(!this.controlList.onlyOnePlaying){
          return 
        }
        let target = res.target
        let audios = document.getElementsByTagName('audio');
        [...audios].forEach((item) => {
          if(item !== target){
            item.pause()
          }
        })
      },
      // 當timeupdate事件大概每秒一次,用來更新音訊流的當前播放時間
      onTimeupdate(res) {
        // console.log('timeupdate')
        // console.log(res)
        this.audio.currentTime = res.target.currentTime
        this.sliderTime = parseInt(this.audio.currentTime / this.audio.maxTime * 100)
      },
      // 當載入語音流元資料完成後,會觸發該事件的回撥函式
      // 語音元資料主要是語音的長度之類的資料
      onLoadedmetadata(res) {
        console.log('loadedmetadata')
        console.log(res)
        this.audio.waiting = false
        this.audio.maxTime = parseInt(res.target.duration)
      },

        downloadMusic() { // 下載音樂
          FileSaver.saveAs(this.url, this.title)
        }
    },
    filters: {
      formatSecond(second = 0) {
        return realFormatSecond(second)
      },
      transPlayPause(value) {
        return value ? '暫停' : '播放'
      },
      transMutedOrNot(value) {
        return value ? '放音' : '靜音'
      },
      transSpeed(value) {
        return '快進: x' + value
      }
    },
    created() {
      this.setControlList()
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .main-wrap{
    padding: 10px 15px;
  }
  .slider {
    display: inline-block;
    width: 100px;
    position: relative;
    top: 14px;
    margin-left: 15px;
  }
  .di {
    display: inline-block;
  }
  .download {
    color: #409EFF;
    margin-left: 15px;
  }
  .dn{
    display: none;
  }
</style>

原文連結 :https://segmentfault.com/a/1190000012453975?utm_source=tuicool&utm_medium=referral