小程序wx.createInnerAudioContext,获取不到时长问题

最近在开发小程序中,需要用到音频播放功能。但在初始化时,使用InnerAudioContext.duration获取不到音频的时长。

Page({
 /**
  * 生命周期函数--监听页面初次渲染完成
  */
  onReady: function () {
    // 创建一个audio
    this.innerAudioContext = wx.createInnerAudioContext();
    // 设置audio的资源地址
    this.innerAudioContext.src = 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?gu;  
    // 直接获取时长,获取到的为0
    console.log(this.innerAudioContext.duration); // 0
    // 延时获取时长,获取到的还是0
    setTimeout(()=> {
      console.log(this.innerAudioContext.duration); // 0
    }, 1000);
  }
})

  

解决方法

1.使用innerAudioContext.onPlay()监听播放获取时长,此方法用于播放音频后获取

Page({
/**
 * 生命周期函数--监听页面初次渲染完成
 */
 onReady: function () {
   // 创建一个audio
   this.innerAudioContext = wx.createInnerAudioContext();
   // 设置audio的资源地址
   this.innerAudioContext.src = 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?gu;  
   // 监听音频播放事件
   this.innerAudioContext.onPlay(() => {
     // 可以获取到音频时长
     console.log(this.innerAudioContext.duration); // 401.475918
   });
 }
})

  

新片场https://www.wode007.com/sites/73286.html 傲视网https://www.wode007.com/sites/73285.html

2.使用innerAudioContext.onCanplay()监听音频进入可以播放状态,此方法用于初始化时获取。

Page({
 /**
  * 生命周期函数--监听页面初次渲染完成
  */
  onReady: function () {
    // 创建一个audio
    this.innerAudioContext = wx.createInnerAudioContext();
    // 设置audio的资源地址
    this.innerAudioContext.src = 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?gu;  
    // 监听音频进入可以播放状态的事件
    this.innerAudioContext.onCanplay(()=> {
      // 必须。可以当做是初始化时长
      this.innerAudioContext.duration;
      // 必须。不然也获取不到时长
      setTimeout(() => {
        console.log(this.innerAudioContext.duration); // 401.475918
      }, 1000)
    })  
  }
})