您可以在页面的 onUnload
生命周期方法中停止当前正在播放的音频并销毁音频对象。下面是您提供的代码的修改版,其中我添加了一个 onUnload
方法来实现这个功能:javascriptCopy
onUnload() {
// 停止音频播放并销毁音频对象
if (this.innerAudioContext) {
this.innerAudioContext.stop()
this.innerAudioContext.destroy()
}
},
methods: {
reset() {
const curUrl = this.data[0].audioUrl;
this.cur = 0
this.creatAudio(curUrl)
},
stop() {
if (this.timer) {
clearInterval(this.timer)
this.timer = null
}
this.isplay = false
},
creatAudio(url) {
// 停止当前正在播放的音频并销毁音频对象
if (this.innerAudioContext) {
this.innerAudioContext.stop()
this.innerAudioContext.destroy()
}
this.innerAudioContext = uni.createInnerAudioContext();
this.innerAudioContext.autoplay = true;
this.innerAudioContext.src = url;
this.innerAudioContext.onPlay(() => {
console.log('开始播放');
});
this.innerAudioContext.onError((res) => {
console.log(res.errMsg);
console.log(res.errCode);
});
},
play() {
if (!this.isplay) {
this.cur = 0;
this.isplay = true;
const curUrl = this.data[this.cur].audioUrl;
this.creatAudio(curUrl)
clearInterval(this.timer);
this.timer = setInterval(() => {
this.cur = (this.cur + 1) % this.data.length;
const curUrl = this.data[this.cur].audioUrl;
this.creatAudio(curUrl)
}, 5000);
}
}
}
在修改后的代码中,onUnload
方法首先检查是否有正在播放的音频,如果有,就停止音频播放并销毁音频对象。在 creatAudio
方法中,我们也添加了停止当前正在播放的音频并销毁音频对象的逻辑。这样,在切换到另一个音频之前,我们就可以停止当前正在播放的音频了。