在点击广告按钮时,发现会重复加载已经在游戏初始化时加载过的音效资源,导致以下问题:
[BundleLoader] 从Bundle data 加载资源: 弹球音效/ui play
index.js? [sm]:33 [BundleLoader] 资源加载成功: data/弹球音效/ui play
index.js? [sm]:7 [AudioManager] 播放UI音效: data/弹球音效/ui play
Error: SystemError (appServiceSDKScriptError)
{"errMsg":"updateTextView:fail 33409 not found"}
Audio.playUISound('data/弹球音效/ui play')Audio.playUISound('data/弹球音效/get money')// 每次播放都重新加载资源
const clip = await this.bundleLoader.loadAssetFromBundle<AudioClip>('data', bundlePath, AudioClip);
BundleLoader的loadAssetFromBundle方法每次都会重新从Bundle加载资源,没有缓存机制。
在AudioManager中添加音频缓存:
// 音频缓存
private audioClipCache: Map<string, AudioClip> = new Map();
private async playSound(audioSource: AudioSource, sfxPath: string, volume: number | undefined, baseVolume: number, soundType: string) {
// 检查缓存中是否已有该音频
let clip = this.audioClipCache.get(cleanPath);
if (!clip) {
// 首次加载并缓存
clip = await this.bundleLoader.loadAssetFromBundle<AudioClip>('data', bundlePath, AudioClip);
this.audioClipCache.set(cleanPath, clip);
console.log(`[AudioManager] 音效已缓存: ${cleanPath}`);
} else {
console.log(`[AudioManager] 使用缓存音效: ${cleanPath}`);
}
audioSource.playOneShot(clip);
}
// 清理缓存
public clearAudioCache() {
console.log(`[AudioManager] 清理音频缓存,共${this.audioClipCache.size}个音效`);
this.audioClipCache.clear();
}
// 获取缓存信息
public getCacheInfo(): {count: number, paths: string[]} {
return {
count: this.audioClipCache.size,
paths: Array.from(this.audioClipCache.keys())
};
}
// Audio静态类中添加缓存管理
static clearAudioCache() {
const manager = AudioManager.getInstance();
if (manager) {
manager.clearAudioCache();
}
}
static getCacheInfo(): {count: number, paths: string[]} {
const manager = AudioManager.getInstance();
if (manager) {
return manager.getCacheInfo();
}
return {count: 0, paths: []};
}
// 现有代码无需修改,自动享受缓存优化
Audio.playUISound('data/弹球音效/ui play');
Audio.playUISound('data/弹球音效/get money');
// 查看缓存状态
const cacheInfo = Audio.getCacheInfo();
console.log(`缓存音效数量: ${cacheInfo.count}`);
console.log(`缓存音效列表:`, cacheInfo.paths);
// 清理缓存(在内存紧张时)
Audio.clearAudioCache();
优化后的表现:
[AudioManager] 从Bundle加载新音效: 弹球音效/ui play[AudioManager] 使用缓存音效: data/弹球音效/ui play