微信小程序: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
  },
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容