vue項目,解決ios下audio無法播放問題

最近在做一個關於aduio的項目,奈何audio在pc端能正常播放,在ios端確無法播放,着實踩了不少的坑!!!
也看了不少的網上的教程,最後的實現結果如下:
在這裏插入圖片描述
1、html代碼

// html
<audio id="audio" :src="src" ref="audio" @timeupdate="updateTime" >該瀏覽器不支持audio屬性</audio>
<div v-if="isMobile">
  <div class="playbtn"  @touchstart="play" v-if="!isPlay"></div>
  <div class="stopbtn"  @touchstart="pause" v-else></div>
</div>
<div v-else>
  <div class="playbtn"  @click="play" v-if="!isPlay"></div>
  <div class="stopbtn"  @click="pause" v-else></div>
</div>

不支持audio元素的瀏覽器會顯示標籤內文字
(1)、audio的屬性
src:音頻地址
autoplay:音頻加載完畢後自動播放
controls:顯示播放控制條
loop:播放完畢後會重複播放
preload:1)auto 預加載音頻視頻。2)metadata 只預加載音頻視頻元數據。 有autoplay時此屬性無效。
(2)、js
play() 播放
pause() 暫停
load() 重新加載
(3)、微信端和手機不能支持自動播放問題
原因是:android ios 內部原因爲了節省流量,規定不自動播放音頻視頻,ios系統下會自動屏蔽audio標籤的自動播放,需要使用一個事件來驅動音頻播放
audio.load()

2、js代碼
手機端用touchstart事件來驅動,pc端用click驅動

export default {
  data () {
    return {
      duration: 0,  // 視頻音頻的總時長
      currentTime: 0, // 播放時間
      isPlay: false, // 是否播放
      width: 0 // 視頻音頻的總時間的長度條
    }
  },
  props: ['src', 'isMobile'],
  computed: {
   // 獲取音頻/視頻的總時間
    durationText () {
      return this._parseTime(this.duration)
    },
    // 獲取音頻/視頻的播放時間
    currentTimeText () {
      return this._parseTime(this.currentTime)
    },
    // 獲取音頻的播放滾動條的長度
    progressBarLength () {
      return this.currentTime / this.duration * this.width
    }
  },
  mounted () {
    this.width = parseInt(window.getComputedStyle(this.$refs.bar).getPropertyValue('width'))
    this.audio = this.$refs.audio
    // 獲取視頻音頻總時長
    this.audio.ondurationchange = () => {
      this.duration = this.audio.duration
    }
  },
  methods: {
   // 獲取視頻/音頻正在播放的時間
    updateTime () {
      this.currentTime = this.audio.currentTime
      if (this.audio.ended) {
        this.isPlay = false
      }
    },
    // 播放
    play () {
      this.audio.load()
      this.audio.play()
      this.isPlay = true
    },
    // 暫停
    pause () {
      this.audio.pause()
      this.isPlay = false
    },
    // 把獲取的視頻音頻時長,轉化成具體的時間格式
    _parseTime (sec) {
      let minutes = parseInt(sec / 60)
      let seconds = parseInt(sec - 60 * minutes)
      return (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds)
    }
  }
}
</script>

相關文章:
https://www.cnblogs.com/volare/p/6759835.html
https://segmentfault.com/q/1010000000390733
https://blog.csdn.net/SoySauce_lm/article/details/86476004
https://www.cnblogs.com/cpqwebfe/p/7543256.html
https://segmentfault.com/q/1010000012624104/a-1020000012624254
https://blog.csdn.net/cmyh100/article/details/80695271

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章