原因:其实是wx的bug,这个问题在开发环境中,并不会遇到。而是真机测试或发版后,就获取不到duration。
解决:我们只要去手动播放音频后,就会抓取到duration。
代码示例
关键代码
this.audioContext.play(); //手动播放音频
完整代码
AudioPlay(file) {this.audioContext = uni.createInnerAudioContext({useWebAudioImplement: true});this.audioContext.src = file.path;this.audioContext.startTime = 0;this.audioContext.play(); //手动播放音频this.audioContext.stop(); //手动停止播放音频this.audioContext.onPlay(() => {console.log('开始播放');})//调用onCanplay使音频进入可以播放状态this.audioContext.onCanplay(() => {console.log(_this?.audioContext?.duration, "duration");let intervalID = setInterval(() => {if (this?.audioContext?.duration !== 0) {const time = Math.floor(this.audioContext.duration);clearInterval(intervalID); // 清除定时器console.log("当前音频长度",this?.audioContext?.duration, "duration");//这里可以做音频的限制if ( time > 60) {this.audioContext = null;uni.showToast({icon: "none",title: "音频不能超过1分钟",});} }}, 500);});},