vue.js 按顺序播放音频

时间:2021-02-05 06:40:42

标签: javascript vue.js html5-audio

Windows、Chrome

我正在尝试按顺序播放多个音频文件

尝试使用时间更新事件、结束事件和播放承诺回调

但它播放 100 -> 5,而不是 100 -> 20 -> 5

出现此错误 https://developers.google.com/web/updates/2017/06/play-request-was-interrupted

如何播放多个音频文件?使用音频缓冲区?

有什么问题吗?

<audio ref="audio-dom" preload="none" />

...

import A from 'sounds/100.wav';
import B from 'sounds/20.wav';
import C from 'sounds/5.wav';

data () {
  return {
    SOUNDS : {
      a : A,
      b : B,
      c : C,
    },
    soundsToPlay : [],
  }
},
computed : {
  _player () {
    return this.$refs['audio-dom']
  },
},
methods : {
  execute () {
    this.soundsToPlay = [this.SOUNDS.a, this.SOUNDS.b, this.SOUNDS.c]
    this._player.pause()
    this._playSound()
  },
}
  1. 使用 timeupdate 事件
...
methods : {
  ...
  _playSound () {
    if (this.soundsToPlay.length < 1) { return }
    let ss = this.soundsToPlay.shift()
    this._player.src = ss

    this._player.addEventListener('timeupdate', this._playSoundRecursive)
    this._player.play()
  },
  _playSoundRecursive () {
    if (this._player.currentTime >= this._player.duration) {
      setTimeout(() => this._playSound(), 5)
    }
  },
}
  1. 使用结束事件
...
methods : {
  ...
  _playSound () {
    if (this.soundsToPlay.length < 1) { return }
    let ss = this.soundsToPlay.shift()
    this._player.src = ss

    this._player.addEventListener('ended', this._playSoundRecursive)
    this._player.play()
  },
  _playSoundRecursive () {
    if (this._player.currentTime >= this._player.duration) {
      setTimeout(() => this._playSound(), 5)
    }
  },
}
  1. 使用游戏承诺
...
methods : {
  ...
  _playSound () {
    if (this.soundsToPlay.length < 1) { return }
    let ss = this.soundsToPlay.shift()
    this._player.src = ss

    let pm = this._player.play()
    pm.then(() => { this._playSound() })
  },
}

0 个答案:

没有答案