項目需求要做一個音頻播器的功能,但是要實現退出小程序后還能播放,在微信聊天頂部出現正在播放的什么音頻的播放標記。然后在網上找了相關的例子發現大多都是退出后音頻會暫停掉,不符合項目需求。查閱微信小程序API文檔,發現可以使用wx.getBackgroundAudioManager()這個api實現退出后還能播放的需求。
上圖就是大概界面,點擊按鈕進行播放,進圖條可以拖拽,點擊列表播放音頻
首先創建全局的音頻播放器
const audioManager = wx.getBackgroundAudioManager()
通過wx.request請求調用接口獲取音頻列表的信息

第二步初始化對象賦值
采用定時器延時賦值,因為請求是異步的方式,有可能會在成功時取不到值
播放與暫停
列表播放
看了下文檔,在onEnded中執行下一首的函數
1 audioManager.onEnded(function() { 2 console.log("onEnded"); 3 console.log("當前狀態", that.data.audioPalyStatus); 4 let nextTimer = setTimeout(function() { 5 if (that.data.showpause === true) { 6 that.bindTapNext() 7 } 8 }, 2000) 9 })
that.data.showpause這是表示沒有點擊暫停按鈕的狀態
1 //自動播放下一首 2 bindTapNext: function() { 3 console.log("播放下一首", 'bindTapNext') 4 let that = this 5 let length = this.data.audiolist.length 6 console.log("當前有多少音頻的長度", length); 7 let audioIndexPrev = this.data.index 8 console.log("當前的index", audioIndexPrev); 9 let audioIndexNow = audioIndexPrev 10 if (audioIndexPrev === length - 1) { 11 12 audioIndexNow = 0 13 } else { 14 audioIndexNow = audioIndexPrev + 1 15 console.log("當前audioIndexNow", audioIndexNow); 16 } 17 setTimeout(function() { 18 that.setData({ 19 index: audioIndexNow, 20 audioPalyStatus: 0, 21 // showstart: false, 22 showpause: true, 23 secondplay: false, 24 max: that.data.max, 25 }) 26 that.setData({ 27 currentobj: that.data.audiolist[that.data.index] 28 }) 29 that.setData({ 30 text: that.data.currentobj.voice_dec, 31 }) 32 console.log("再次的index", that.data.index); 33 console.log("下一首的嗎", that.data.currentobj); 34 console.log("第0首", that.data.audiolist[0], '第一首', that.data.audiolist[1]); 35 if (that.data.showpause == true) { 36 // that.start() 37 that.setData({ 38 secondplay: false, 39 }) 40 audioManager.src = that.data.currentobj.voicefile 41 audioManager.title = that.data.currentobj.voice_name 42 audioManager.coverImgUrl = that.data.currentobj.urlimage 43 // max = that.data.currentobj.voice_times 44 } 45 }, 1000) 46 47 },
基本完成音樂播放功能