Javascript 在vue中构建音频播放器;如何在更改绑定:src后开始播放音频?
问题示例: (警告,加载时将开始播放音乐) 我有一个音频标签,看起来像Javascript 在vue中构建音频播放器;如何在更改绑定:src后开始播放音频?,javascript,vue.js,html5-audio,Javascript,Vue.js,Html5 Audio,问题示例: (警告,加载时将开始播放音乐) 我有一个音频标签,看起来像 <audio :src="current" @timeupdate="time = $event.target.currentTime" ref="audio" @ended="nextTrack()" autoload preload="auto" autoplay> </audio> 当播放列表中有曲目时,它工作正常--此。当前设置为下一
<audio
:src="current"
@timeupdate="time = $event.target.currentTime"
ref="audio"
@ended="nextTrack()"
autoload preload="auto" autoplay>
</audio>
当播放列表中有曲目时,它工作正常--此。当前
设置为下一个曲目,开始正常播放
但是,如果先清除播放列表(当播放列表为空时按“下一曲目”按钮),然后添加曲目并按“播放”,则曲目不会开始播放。我在音频标签上调用了play()
,但它仍然不播放
我相信这可能是因为我在设置this.current
后立即调用this.$refs.audio.play()
,所以vue可能没有及时更新:src,以便在正确的src上调用play()
,但我尝试了设置超时,但它没有修复它。此外,我认为当有播放列表时,nextTrack
会起作用,因为设置了autoplay
,而不是因为我正在调用load/play
如何更改音频标签的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处理状态更新,然后我可以在音频参考上调用play
正在工作的JSFIDLE:(再次,音频自动播放警告)
this.$nextTick(() => {
if (this.playing) {
this.$refs.audio.play()
}
})