uni-app如何使用onCanplay获取音频时长完整代码

在一些祝福类或婚姻类的小程序或网站中,通常可以看见背景音乐的使用。

那么当我们设置背景音乐后,如果需要获取音频的时长要如何实现呢?

本篇文中介绍使用onCanplay()来告诉你如何获取音频的时长

<script>
const innerAudioContext = uni.createInnerAudioContext();
export default {
data() {
return {
};
},
methods:{
getVTime(){
innerAudioContext.src = '音频地址'
innerAudioContext.onCanplay(()=>{
let intervalID = setInterval(() => {
if (innerAudioContext.duration !== 0) {
clearInterval(intervalID); // 清除定时器
//音频时长
console.log(innerAudioContext.duration)
}
}, 500);
})
}
}
}
</script>

关键点:

    setInterval的使用是为了防止你获取的音频时长为0或undefined情况的出现。

六月初字帖坊小程序 你想要的字帖模板及工具,这里都有!