解决 uni-app 中 onTimeUpdate 方法无法在自动播放的时候不生效问题

解决 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)
		}
			
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值