<audio>标签实现设置播放次数的功能

标签实现设置播放次数的功能

audio有一个事件: end
开始思路是:通过给标签设置loop属性后,监听播放结束的次数,来控制播放。

function playTimes(elem, times) {
    var start = 0;
    elem.addEventListener("ended",function() {
        start++;
        start == times && elem.pause();
    });
}

这种思路行不通,因为循环播放功能时,无法监听ended事件。
换个思路是:不设置循环属性,通过监听播放结束的次数来控制.在语音结束后再次调用播放方法.

mounted(){
    //首次进入页面时
    this.audioPlay = this.$refs.audio
    this.audioPlay.addEventListener('ended',this.limitPlay)
  },
//播放语音
    playTip(){
      this.testAutoPlay()
      .then((res)=>{
        console.log(res)
      })
    },
    //测试是不是可以自动播放并返回结果
    testAutoPlay () {
      let autoplay = false
      return new Promise(resolve => {
        let audioPlay = this.$refs.audio
        audioPlay.src= this.audioUrl
        // audioPlay.currentTime = 0; //从头开始播放提示音
        // audioPlay.muted = true;    //静音播放
        // play返回的是一个promise
        audioPlay.play().then(() => {
          // 支持自动播放
          autoplay = true;
        }).catch(() => {
          // 不支持自动播放
          autoplay = false;
        }).finally(() => {
          // 告诉调用者结果
          resolve(autoplay);
        });
      });
    },
//循环播放次数判断
    limitPlay(){
      this.start++;
      console.log("次数限制"+this.start)
      if(this.start <= this.playTimes){
        this.playTip()
      }else{
        this.audioPlay.pause()
      }
    }

这种思路需要浏览器支持语音播放才可以,谷歌浏览器会拦截自动播放,所以需要设置一下浏览器声音属性,具体怎么设置请看这里.希望对你有帮助.

猜你喜欢

转载自blog.csdn.net/weixin_46995731/article/details/122828226