From 35ddced9d440cdb9b5b3f2dafb8b91dd8e950277 Mon Sep 17 00:00:00 2001 From: WindowBird <13870814+windows-bird@user.noreply.gitee.com> Date: Tue, 25 Nov 2025 16:06:05 +0800 Subject: [PATCH] =?UTF-8?q?=E9=A6=96=E9=A1=B5=E9=9F=B3=E9=A2=91=E6=92=AD?= =?UTF-8?q?=E6=94=BE=E5=8D=95=E4=BE=8B=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pages/index/index.vue | 49 +++++++++++++++++++++++-------------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/pages/index/index.vue b/pages/index/index.vue index 2804908..edda128 100644 --- a/pages/index/index.vue +++ b/pages/index/index.vue @@ -182,6 +182,11 @@ export default { onShow() { // 启动跑马灯(方法内部会检查是否有文本) this.startMarquee(); + // this.playAudio(); + }, + onHide() { + // 页面隐藏时停止音频播放,确保只在当前页面播放 + this.stopAudio(); }, onUnload() { this.stopMarquee(); @@ -306,9 +311,9 @@ export default { this.startMarquee(); // 自动播放音频 - // if (this.templeData.audioUrl) { - // this.playAudio(); - // } + if (this.templeData.audioUrl) { + this.playAudio(); + } console.log("寺庙数据加载成功"); } else { @@ -475,24 +480,25 @@ export default { }, /** - * 播放音频 + * 播放音频 - 实现单例模式 */ playAudio() { if (!this.templeData.audioUrl) { - uni.showToast({ - title: "暂无音频资源", - icon: "none", - }); + // uni.showToast({ + // title: "暂无音频资源", + // icon: "none", + // }); return; } try { - // 如果已经在播放,先停止 + // 确保全局只有一个音频实例在播放(单例模式) + // 如果当前页面已有音频实例,先停止 if (this.audioContext) { this.stopAudio(); } - // 创建音频上下文 + // 创建新的音频上下文实例 this.audioContext = uni.createInnerAudioContext(); this.audioContext.src = this.templeData.audioUrl; this.audioContext.loop = true; // 循环播放 @@ -501,10 +507,6 @@ export default { this.audioContext.onPlay(() => { console.log("音频开始播放"); this.isAudioPlaying = true; - // uni.showToast({ - // title: "音频已开启", - // icon: "none", - // }); }); this.audioContext.onError((err) => { @@ -534,19 +536,20 @@ export default { }, /** - * 停止音频 + * 停止音频 - 确保资源正确释放 */ stopAudio() { if (this.audioContext) { - this.audioContext.stop(); - this.audioContext.destroy(); - this.audioContext = null; + try { + this.audioContext.stop(); + this.audioContext.destroy(); + } catch (error) { + console.error("停止音频时出错:", error); + } finally { + this.audioContext = null; + this.isAudioPlaying = false; + } } - this.isAudioPlaying = false; - // uni.showToast({ - // title: "音频已关闭", - // icon: "none", - // }); }, }, };