setTimeout了也是duration还是0,奇怪的是另外一个小程序同样的代码,同样的环境是可以获取到的
var src ='share/static/voice/openauto.wav'
var innerAudioContext = wx.createInnerAudioContext()
innerAudioContext.autoplay = true
innerAudioContext.src = src
console.log(innerAudioContext.duration);
innerAudioContext.onPlay(() => {
console.log('onPlay:开始播放');
});
innerAudioContext.onError((res) => {
console.log("onError:" + res.errMsg);
});
innerAudioContext.onCanplay(()=> {
innerAudioContext.duration;
setTimeout(() => {console.log(innerAudioContext.duration);}, 3000)
});
试试这么写
innerAudioContext.onCanplay(function get_duration() { if (innerAudioContext.duration) { // 做你想做的事情 console.log(innerAudioContext.duration) } else { setTimeout(get_duration, 0) } })
const tempAudioContext = wx.createInnerAudioContext()
tempAudioContext .src = 'xxxxxx'
tempAudioContext.onPlay(function() {
console.log(tempAudioContext.duration)
tempAudioContext.stop()
})
tempAudioContext.volume = 0
tempAudioContext.play()
实在不行,建议结合官方云服务,用node端第三方库计算音频的duration,我的音频因为本身就是在云函数里拿到的,所以直接用第三方nodejs库 music-metadata 算了一下再返回小程序端,这种计算还是服务端靠谱,客户端不同设备有各种坑