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

更新日期: 2018-11-08阅读: 6k标签: audio

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

Page({
 /**
  * 生命周期函数--监听页面初次渲染完成
  */
  onReady: function () {
    // 创建一个audio
    this.innerAudioContext = wx.createInnerAudioContext();
    // 设置audio的资源地址
    this.innerAudioContext.src = 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E06DCBDC9AB7C49FD713D632D313AC4858BACB8DDD29067D3C601481D36E62053BF8DFEAF74C0A5CCFADD6471160CAF3E6A&fromtag=46';  
    // 直接获取时长,获取到的为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?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E06DCBDC9AB7C49FD713D632D313AC4858BACB8DDD29067D3C601481D36E62053BF8DFEAF74C0A5CCFADD6471160CAF3E6A&fromtag=46';  
   // 监听音频播放事件
   this.innerAudioContext.onPlay(() => {
     // 可以获取到音频时长
     console.log(this.innerAudioContext.duration); // 401.475918
   });
 }
})


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

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


原文来源:https://segmentfault.com/a/1190000016952617


链接: https://www.fly63.com/article/detial/1297

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!