1 创建背景音频管理器
const audioContext = wx.getBackgroundAudioManager()
2 在app.json里配置
“requiredBackgroundModes”: [“audio”]
3 配置背景音频管理器的title属性(必传)
//1 請求数据
// 請求歌曲詳情
getSongDetail(id).then(res => {
ctx.currentSong = res.songs[0]
ctx.durationTime = res.songs[0].dt
audioContext.title=ctx.currentSong.al.name
})
//2 使用audioContext播放歌曲
audioContext.stop()
// 变量要写在模板字符串里
audioContext.src = `http://music.163.com/song/media/outer/url?id=${id}.mp3`
//在这里配置title
//等到异步的数据请求 getSongDetail(id)拿到歌曲的数据后再把title设置为真正的歌曲名字
audioContext.title = ctx.currentSong.id
audioContext.autoplay = true
// 3 监听audioContext的一些事件 只有在第一次才监听
if (ctx.isFirstPlay) {
this.dispatch("setupAudioContextListener")
ctx.isFirstPlay = false
}
本来第一步是用 wx.createAudioContext() 但是我为了要在退出小程序后依然能播放歌曲 就改了第一步 然后增加第二三步即可