首页音频播放单例模式

This commit is contained in:
WindowBird 2025-11-25 16:06:05 +08:00
parent 4b750c78b7
commit 35ddced9d4

View File

@ -182,6 +182,11 @@ export default {
onShow() { onShow() {
// //
this.startMarquee(); this.startMarquee();
// this.playAudio();
},
onHide() {
//
this.stopAudio();
}, },
onUnload() { onUnload() {
this.stopMarquee(); this.stopMarquee();
@ -306,9 +311,9 @@ export default {
this.startMarquee(); this.startMarquee();
// //
// if (this.templeData.audioUrl) { if (this.templeData.audioUrl) {
// this.playAudio(); this.playAudio();
// } }
console.log("寺庙数据加载成功"); console.log("寺庙数据加载成功");
} else { } else {
@ -475,24 +480,25 @@ export default {
}, },
/** /**
* 播放音频 * 播放音频 - 实现单例模式
*/ */
playAudio() { playAudio() {
if (!this.templeData.audioUrl) { if (!this.templeData.audioUrl) {
uni.showToast({ // uni.showToast({
title: "暂无音频资源", // title: "",
icon: "none", // icon: "none",
}); // });
return; return;
} }
try { try {
// //
//
if (this.audioContext) { if (this.audioContext) {
this.stopAudio(); this.stopAudio();
} }
// //
this.audioContext = uni.createInnerAudioContext(); this.audioContext = uni.createInnerAudioContext();
this.audioContext.src = this.templeData.audioUrl; this.audioContext.src = this.templeData.audioUrl;
this.audioContext.loop = true; // this.audioContext.loop = true; //
@ -501,10 +507,6 @@ export default {
this.audioContext.onPlay(() => { this.audioContext.onPlay(() => {
console.log("音频开始播放"); console.log("音频开始播放");
this.isAudioPlaying = true; this.isAudioPlaying = true;
// uni.showToast({
// title: "",
// icon: "none",
// });
}); });
this.audioContext.onError((err) => { this.audioContext.onError((err) => {
@ -534,19 +536,20 @@ export default {
}, },
/** /**
* 停止音频 * 停止音频 - 确保资源正确释放
*/ */
stopAudio() { stopAudio() {
if (this.audioContext) { if (this.audioContext) {
try {
this.audioContext.stop(); this.audioContext.stop();
this.audioContext.destroy(); this.audioContext.destroy();
} catch (error) {
console.error("停止音频时出错:", error);
} finally {
this.audioContext = null; this.audioContext = null;
}
this.isAudioPlaying = false; this.isAudioPlaying = false;
// uni.showToast({ }
// title: "", }
// icon: "none",
// });
}, },
}, },
}; };