解决 uni-app 中 onTimeUpdate 方法无法在自动播放的时候不生效问题
在uni-app 使用频的时候, 一般是在created方法里面设置 播放/暂停/等方法, 如果加上 自动播放, 就会出现音频自动播放了,但是onTimeUpdate()方法无法触发
这是因为 这些方法都是回调方法, 属于异步事件,有一定延迟, 所以我们需要使用定时器来 将自动播放也设为异步事件
这是出错的代码:
methods: {
//点击播放按钮
play() {
this.audio.play()
this.loading = true
},
},
created() {
if (this.src) {
this.audio.src = this.src
this.autoplay && this.play() // 错误的开始自动播放
}
// 跨过静音开关
this.audio.obeyMuteSwitch = false
if (!this.duration) {
this.duration = this.audio.duration
}
//音频播放事件
this.audio.onPlay(() => {
console.log('开始播放')
this.paused = false
this.loading = false
})
//音频进度更新事件
this.audio.onTimeUpdate(() => {
if (!this.seek) {
this.current = this.audio.currentTime
}
if (!this.duration) {
this.duration = this.audio.duration
}
})
//音频暂停事件
this.audio.onPause(() => {
this.paused = true
})
//音频结束事件
this.audio.onEnded(() => {
if (this.continue) {
this.audio.paly()
} else {
this.paused = true
this.current = 0
}
})
//音频完成更改进度事件
this.audio.onSeeked(() => {
this.seek = false
})
},
beforeDestroy(){
this.audio.destroy()
}
这是修改过的代码:
if (this.src) {
this.audio.src = this.src
setTimeout(() => {
this.autoplay && this.play() // 正确的自动播放
}, 500)
}