小程序innerAudioContext的使用

实现播放音频很简单,直接上代码啦:

this.innerAudioContext = wx.createInnerAudioContext();

var voicePath = this.data.voiceTempFilePath;

this.innerAudioContext.src = voicePath;  

this.innerAudioContext.play();

this.innerAudioContext.onEnded((res) => {

 console.log('播放结束!');

 })

 // 播放音频失败的回调

this.innerAudioContext.onError((res) => { 

console.log('播放音频失败' + res);

})

 this.innerAudioContext.onStop((res) => {

      console.log('停止播放!');

  })

关于音频播放的几个callback可以根据需求自行添加,如需更多,官方文档贴给你:

https://developers.weixin.qq.com/miniprogram/dev/api/media/audio/InnerAudioContext.html

这里主要想说的是,做的时候要实现点击播放,我把上面代码写入一个方法中,然后点击调用,发现音频可以播放,但是无法停止,

也了解了一下,发现很多人也遇到这个问题.解决方法是:把音频实例的创建以及callback写入onload()中,这样就正常了.音频实例以及callback不用反复创建.代码如下:

  /**

  * 生命周期函数--监听页面加载

  */

  onLoad: function (options) {

    this.registerAudioContext();

  },

// 注册音频

  registerAudioContext:function () {

    this.innerAudioContext = wx.createInnerAudioContext();

    this.innerAudioContext.onEnded((res) => {

    })

    this.innerAudioContext.onError((res) => {

      // 播放音频失败的回调

      console.log('播放音频失败' + res);

    })

    this.innerAudioContext.onStop((res) => {

      console.log('播放结束!');

    })

  },

作者:Mr_Atom
链接:https://www.jianshu.com/p/c6310af79df8
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值