javascript - 在 vue 中构建音频播放器;如何在更改绑定(bind) :src? 后让音频开始播放

标签 javascript vue.js html5-audio

问题示例: https://jsfiddle.net/manfrin/tnszqwpd/58/ (警告,加载时将开始播放音乐)。

我有一个音频标签,看起来像

  <audio 
    :src="current" 
    @timeupdate="time = $event.target.currentTime" 
    ref="audio" 
    @ended="nextTrack()" 
    autoload preload="auto" autoplay>
  </audio>

当轨道结束时,它会调用 nextTrack 来更改 src,如下所示:

nextTrack: function () {
    if (this.playlist.length > 0) {
    this.current = this.playlist.shift()
    this.$refs.audio.load()
    this.$refs.audio.play()
    this.playing = true
  } else {
    this.current = "";
    this.playing = false;
  }
},

当播放列表中有轨道时,它工作正常 -- this.current 设置为下一首轨道并开始正常播放。

但是,如果您先清除播放列表(播放列表为空时按“下一首轨道”按钮),然后添加轨道并按播放,则轨道不会开始播放。我在音频标签上调用了 play(),它仍然没有播放。

我相信这可能是因为我在设置 this.current 之后调用了 this.$refs.audio.play(),所以也许 vue 没有更新:src 及时在正确的 src 上调用 play(),但我尝试了 setTimeout 但它没有修复它。此外,我认为 nextTrack 在有播放列表时起作用,因为设置了 autoplay,而不是因为我正在调用加载/播放。

如何更改音频标签的 src 并使其以相同的顺序播放?

最佳答案

我已经为此苦苦挣扎了几天,最后我决定发布一个 StackOverflow 问题,当然 5 分钟后我就弄明白了。

因为我需要依赖于我在 nextTrack() 方法中设置的状态,所以我可以使用 this.$nextTick。我的 nextTrack/play 看起来像这样:

  nextTrack: function () {
    if (this.playlist.length > 0) {
    this.current = this.playlist.shift()
    this.playing = true
    this.play()
  } else {
    this.current = "";
    this.playing = false;
  }
},
play: function () {
    if (!this.playing) {
    if (!this.current && this.playlist.length > 0) {
      this.$refs.audio.pause()
      this.current = this.playlist.shift()
    }
    if (!this.current) {
      this.playing = false
    } else {
      this.playing = true
    }
    this.$nextTick(() => {
        if (this.playing) {
        this.$refs.audio.play()
      }
    })
  } else {
    this.$refs.audio.pause()
    this.playing = false
  }
},

重要的部分是这个,具体来说:

    this.$nextTick(() => {
        if (this.playing) {
        this.$refs.audio.play()
      }
    })

nextTick 允许我等到 vue 处理完状态更新,然后我可以在音频 ref 上调用播放。

工作 jsfiddle:https://jsfiddle.net/manfrin/tnszqwpd/72/ (同样,音频自动播放警告)。

关于javascript - 在 vue 中构建音频播放器;如何在更改绑定(bind) :src? 后让音频开始播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51239307/

相关文章:

javascript - 为什么在同一位置写入两次时写入 Canvas 的文本会变暗?

javascript - 如何连接两个 javascript 变量(动态)

javascript - 如何在 Javascript 中将方法转换为递归函数?

javascript - 如何在 canplay 事件中设置 HTMLMediaElement 的 .currentTime,调用播放并避免调度暂停事件?

javascript - JQuery UI,将可排序与可删除相结合

vue.js - Vuetify 2.x v-data-table 键盘命令/导航

javascript - 获取缓存响应 - 无缓存 header 未按预期工作

javascript - 如何用 JavaScript 改变音调?

javascript - 尝试通过javascript从音频文件中获取分贝级别

javascript - zombie 代码中的语法 `async/await` 是什么?