微信小程序-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('播放结束!');

    })

  },

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容