首页音频播放单例模式
This commit is contained in:
parent
4b750c78b7
commit
35ddced9d4
|
|
@ -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",
|
||||
// });
|
||||
},
|
||||
},
|
||||
};
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user