Error screenshot
The bottom this.setData() error can be ignored, it is a problem with the value of this
solve
- When you need to play and pause functions, you need to put the audio and its src outside the Page.
- The two methods audioCtx.onPlay() and audioCtx.onError() cannot be missing, and they need to be placed before the play() method
- If {useWebAudioImplement:true} is added in wx.createInnerAudioContext(), remove it.
//需要播放暂停音频功能时,需要将这两个变量放在 Page()上面
let audioCtx=wx.createInnerAudioContext()
audioCtx.src='http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3' //填入你自己的音频链接
Page({
data: {
isPlay: false,
},
playMusic(){
audioCtx.onPlay(()=>{
console.log("开始播放");
})
audioCtx.onError((res)=>{
wx.showToast({
title: '音乐播放错误',
icon: 'error',
duration: 3000
})
})
let isPlay = !this.data.isPlay //控制播放和暂停的变量
this.setData({
isPlay:isPlay
})
if(isPlay){
audioCtx.play()
audioCtx.loop = true;
}else{
audioCtx.pause()
}
},
},
onLoad() {
this.playMusic(); //加载完毕,开始播放
},
});