问题示例: 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/