微信小程序:InnerAudioContext 音频播放

英语音标.JPG

界面如上图所示,实现效果,点击音标或单词,播放对应的音频。

js代码

1. 首先定义 innerAudioContext 实例

const innerAudioContext = wx.createInnerAudioContext({
  useWebAudioImplement: true // 默认关闭。对于短音频、播放频繁的音频建议开启此选项
})

2. 初始化音频监听事件

代码中定义了自动开始播放 innerAudioContext.autoplay = true

  onLoad(options) {
    // 初始化音频事件
    this.initAudioEvent()
  },

  // 初始化音频事件
  initAudioEvent() {
    innerAudioContext.autoplay = true
    innerAudioContext.onCanplay(() => {
      console.log('onCanplay')
    }) 
    innerAudioContext.onPlay(() => {
      console.log('onPlay')
      wx.showLoading({
        title: '播放中',
        mask: true,
      })
    })   
    innerAudioContext.onPause(() => {
      console.log('onPause')
    }) 
    innerAudioContext.onStop(() => {
      console.log('onStop')
    }) 
    innerAudioContext.onEnded(() => {
      console.log('onEnded')
      innerAudioContext.src = 'null.m4a'
      wx.hideLoading({
        success: (res) => {},
      })
    })
    innerAudioContext.onError((res) => {
      console.log('onError')
      console.log(res.errMsg)
      console.log(res.errCode)
    }) 
    innerAudioContext.onWaiting(() => {
      console.log('onWaiting')
    }) 
  },

3. 页面点击执行 onPlaySound 播放声音

直接设置音频地址后会自动播放音频 innerAudioContext.src

音频地址无误的情况下监听事件执行的顺序如下:
1)onCanplay
2)onPlay
3)onPause
4)onEnded
所以在 onPlaySound 方法中弹出 loading 提示框,mask=true,防止重复点击音频文件

另外在 onEnded 监听事件中隐藏 loading 提示框

需注意 onEnded 监听事件中,单播放结束,赋予了一个错误的音频地址 innerAudioContext.src = 'null.m4a'
其目的是当点击相同的音频文件时依然能够播放

  // 播放声音
  onPlaySound: function(e) {
    wx.showLoading({
      title: '请稍后',
      mask: true,
    })
    let url = '可播放的音频文件地址.m4a'
    this.playAudio(url)
  },

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

推荐阅读更多精彩内容