AudioManager.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. import { _decorator, Component, AudioClip, AudioSource, resources, Node, find, director, sys } from 'cc';
  2. import { GameManager } from '../LevelSystem/GameManager';
  3. import { BundleLoader } from '../Core/BundleLoader';
  4. import { SaveDataManager } from '../LevelSystem/SaveDataManager';
  5. const { ccclass, property } = _decorator;
  6. @ccclass('AudioManager')
  7. export class AudioManager extends Component {
  8. @property({ type: AudioSource, tooltip: '背景音乐播放器' })
  9. public musicAudioSource: AudioSource = null;
  10. @property({ type: AudioSource, tooltip: 'UI音效播放器' })
  11. public uiSoundAudioSource: AudioSource = null;
  12. @property({ type: AudioSource, tooltip: '敌人音效播放器' })
  13. public enemySoundAudioSource: AudioSource = null;
  14. @property({ type: AudioSource, tooltip: '环境音效播放器' })
  15. public environmentSoundAudioSource: AudioSource = null;
  16. @property({ type: AudioSource, tooltip: '武器音效播放器' })
  17. public weaponSoundAudioSource: AudioSource = null;
  18. private musicVolume: number = 0.8;
  19. private uiSoundVolume: number = 0.8;
  20. private enemySoundVolume: number = 0.8;
  21. private environmentSoundVolume: number = 0.8;
  22. private weaponSoundVolume: number = 0.8;
  23. private soundEffectVolume: number = 0.8;
  24. private currentMusicClip: AudioClip = null;
  25. private bundleLoader: BundleLoader = null;
  26. private audioClipCache: Map<string, AudioClip> = new Map();
  27. // 并发播放保护
  28. private _musicRequestId: number = 0;
  29. private _currentMusicPath: string | null = null;
  30. // 单例实例
  31. private static _instance: AudioManager = null;
  32. onLoad() {
  33. // 设置单例(在 onLoad 阶段更早创建,确保静态调用可用)
  34. if (AudioManager._instance === null) {
  35. AudioManager._instance = this;
  36. // 如需跨场景保留,可取消注释以下两行
  37. // this.node.parent = null;
  38. // director.addPersistRootNode(this.node);
  39. } else {
  40. this.node.destroy();
  41. return;
  42. }
  43. this.bundleLoader = BundleLoader.getInstance();
  44. this.initializeAudioSources();
  45. // 初始化后尝试应用存档中的音频设置
  46. this.applyPersistedSettings();
  47. }
  48. public static getInstance(): AudioManager {
  49. return AudioManager._instance;
  50. }
  51. private initializeAudioSources() {
  52. console.log('[AudioManager] 开始初始化音频源');
  53. if (!this.musicAudioSource) {
  54. console.log('[AudioManager] 创建音乐播放器AudioSource');
  55. const musicNode = new Node('MusicPlayer');
  56. this.node.addChild(musicNode);
  57. this.musicAudioSource = musicNode.addComponent(AudioSource);
  58. this.musicAudioSource.volume = this.musicVolume;
  59. console.log('[AudioManager] 音乐播放器AudioSource创建完成');
  60. } else {
  61. console.log('[AudioManager] 音乐播放器AudioSource已存在');
  62. }
  63. if (!this.uiSoundAudioSource) {
  64. console.log('[AudioManager] 创建UI音效播放器AudioSource');
  65. const uiSfxNode = new Node('UISoundPlayer');
  66. this.node.addChild(uiSfxNode);
  67. this.uiSoundAudioSource = uiSfxNode.addComponent(AudioSource);
  68. this.uiSoundAudioSource.volume = this.uiSoundVolume;
  69. }
  70. if (!this.enemySoundAudioSource) {
  71. const enemySfxNode = new Node('EnemySoundPlayer');
  72. this.node.addChild(enemySfxNode);
  73. this.enemySoundAudioSource = enemySfxNode.addComponent(AudioSource);
  74. this.enemySoundAudioSource.volume = this.enemySoundVolume;
  75. }
  76. if (!this.environmentSoundAudioSource) {
  77. const envSfxNode = new Node('EnvironmentSoundPlayer');
  78. this.node.addChild(envSfxNode);
  79. this.environmentSoundAudioSource = envSfxNode.addComponent(AudioSource);
  80. this.environmentSoundAudioSource.volume = this.environmentSoundVolume;
  81. }
  82. if (!this.weaponSoundAudioSource) {
  83. const weaponSfxNode = new Node('WeaponSoundPlayer');
  84. this.node.addChild(weaponSfxNode);
  85. this.weaponSoundAudioSource = weaponSfxNode.addComponent(AudioSource);
  86. this.weaponSoundAudioSource.volume = this.weaponSoundVolume;
  87. }
  88. console.log('[AudioManager] 音频源初始化完成');
  89. console.log(`[AudioManager] musicAudioSource: ${this.musicAudioSource ? '已创建' : '未创建'}`);
  90. // 设置初始音量
  91. this.updateAllVolumes();
  92. }
  93. // 从存档或本地 audioSettings 恢复音量与开关状态
  94. private applyPersistedSettings() {
  95. try {
  96. const sdm = SaveDataManager.getInstance();
  97. let musicEnabled: boolean | undefined = undefined;
  98. let soundEnabled: boolean | undefined = undefined;
  99. let musicVolume: number | undefined = undefined;
  100. let soundVolume: number | undefined = undefined;
  101. if (sdm && typeof sdm.getSetting === 'function') {
  102. musicEnabled = sdm.getSetting('musicEnabled');
  103. soundEnabled = sdm.getSetting('soundEnabled');
  104. musicVolume = sdm.getSetting('musicVolume');
  105. soundVolume = sdm.getSetting('soundVolume');
  106. }
  107. // 兼容旧的本地键 audioSettings(如果存档未初始化或缺值)
  108. if (musicEnabled === undefined || soundEnabled === undefined || musicVolume === undefined || soundVolume === undefined) {
  109. const raw = sys?.localStorage?.getItem('audioSettings');
  110. if (raw) {
  111. try {
  112. const parsed = JSON.parse(raw);
  113. musicEnabled = musicEnabled ?? parsed?.musicEnabled;
  114. soundEnabled = soundEnabled ?? parsed?.soundEffectEnabled;
  115. musicVolume = musicVolume ?? parsed?.musicVolume;
  116. soundVolume = soundVolume ?? parsed?.soundEffectVolume;
  117. } catch (e) {
  118. // 无需处理解析错误
  119. }
  120. }
  121. }
  122. // 默认值与裁剪
  123. const finalMusicEnabled = musicEnabled !== false;
  124. const finalSoundEnabled = soundEnabled !== false;
  125. const finalMusicVolume = typeof musicVolume === 'number' ? Math.max(0, Math.min(1, musicVolume)) : this.musicVolume;
  126. const finalSoundVolume = typeof soundVolume === 'number' ? Math.max(0, Math.min(1, soundVolume)) : this.soundEffectVolume;
  127. // 应用到管理器内部状态
  128. this.musicVolume = finalMusicEnabled ? finalMusicVolume : 0;
  129. this.soundEffectVolume = finalSoundEnabled ? finalSoundVolume : 0;
  130. this.uiSoundVolume = this.soundEffectVolume;
  131. this.enemySoundVolume = this.soundEffectVolume;
  132. this.environmentSoundVolume = this.soundEffectVolume;
  133. this.weaponSoundVolume = this.soundEffectVolume;
  134. this.updateAllVolumes();
  135. console.log(`[AudioManager] 从存档恢复音量:music=${this.musicVolume}, sfx=${this.soundEffectVolume}`);
  136. } catch (err) {
  137. // 安静失败,不影响后续逻辑
  138. console.warn('[AudioManager] 恢复音频设置失败,使用默认值');
  139. }
  140. }
  141. public async playMusic(musicPath: string, loop: boolean = true) {
  142. if (!this.musicAudioSource) {
  143. console.warn('[AudioManager] 音乐播放器未初始化');
  144. return;
  145. }
  146. // 避免重复请求同一首已在播放的音乐
  147. if (this._currentMusicPath === musicPath && this.musicAudioSource.playing) {
  148. this.musicAudioSource.loop = loop;
  149. console.log(`[AudioManager] 已在播放目标音乐,忽略重复请求: ${musicPath}`);
  150. return;
  151. }
  152. const requestId = ++this._musicRequestId; // 为本次播放分配请求ID
  153. console.log(`[AudioManager] 发起音乐播放请求#${requestId}: ${musicPath}`);
  154. try {
  155. const bundlePath = musicPath.replace('data/', '').replace(/\.(mp3|wav|ogg)$/i, '');
  156. const clip = await this.bundleLoader.loadAssetFromBundle<AudioClip>('data', bundlePath, AudioClip);
  157. // 若在加载期间有新的播放请求,丢弃本次播放
  158. if (requestId !== this._musicRequestId) {
  159. console.log(`[AudioManager] 丢弃过期音乐请求#${requestId}: ${musicPath}(当前请求ID为#${this._musicRequestId})`);
  160. return;
  161. }
  162. // 保险:在开始新音乐前停止当前播放,避免叠加
  163. if (this.musicAudioSource.playing) {
  164. this.musicAudioSource.stop();
  165. }
  166. this.currentMusicClip = clip;
  167. this._currentMusicPath = musicPath;
  168. this.musicAudioSource.clip = clip;
  169. this.musicAudioSource.loop = loop;
  170. this.musicAudioSource.play();
  171. console.log(`[AudioManager] 播放音乐#${requestId}: ${musicPath}`);
  172. } catch (error) {
  173. console.error(`[AudioManager] 加载音乐失败: ${musicPath}`, error);
  174. }
  175. }
  176. public stopMusic() {
  177. console.log('[AudioManager] stopMusic方法被调用');
  178. console.log(`[AudioManager] musicAudioSource状态: ${this.musicAudioSource ? '存在' : '不存在'}`);
  179. // 取消所有正在进行的音乐加载/播放请求
  180. this._musicRequestId++;
  181. console.log(`[AudioManager] 取消到请求ID#${this._musicRequestId}(后续仅处理更新后的请求)`);
  182. if (this.musicAudioSource) {
  183. console.log(`[AudioManager] musicAudioSource.playing: ${this.musicAudioSource.playing}`);
  184. console.log(`[AudioManager] currentMusicClip: ${this.currentMusicClip ? this.currentMusicClip.name : '无'}`);
  185. if (this.musicAudioSource.playing) {
  186. this.musicAudioSource.stop();
  187. console.log('[AudioManager] 停止音乐播放');
  188. } else {
  189. console.log('[AudioManager] 音乐未在播放,无需停止');
  190. }
  191. this.currentMusicClip = null;
  192. this._currentMusicPath = null;
  193. this.musicAudioSource.clip = null;
  194. console.log('[AudioManager] 已清除音乐剪辑引用');
  195. } else {
  196. console.warn('[AudioManager] 音乐播放器未初始化,无法停止音乐');
  197. }
  198. }
  199. public pauseMusic() {
  200. if (this.musicAudioSource && this.musicAudioSource.playing) {
  201. this.musicAudioSource.pause();
  202. console.log('[AudioManager] 暂停音乐播放');
  203. }
  204. }
  205. public resumeMusic() {
  206. if (this.musicAudioSource && this.currentMusicClip && !this.musicAudioSource.playing) {
  207. this.musicAudioSource.play();
  208. console.log('[AudioManager] 恢复音乐播放');
  209. }
  210. }
  211. public playSoundEffect(sfxPath: string, volume?: number) {
  212. this.playSound(this.uiSoundAudioSource, sfxPath, volume, this.soundEffectVolume, '音效');
  213. }
  214. public playUISound(sfxPath: string, volume?: number) {
  215. this.playSound(this.uiSoundAudioSource, sfxPath, volume, this.uiSoundVolume, 'UI音效');
  216. }
  217. public playEnemySound(sfxPath: string, volume?: number) {
  218. this.playSound(this.enemySoundAudioSource, sfxPath, volume, this.enemySoundVolume, '敌人音效');
  219. }
  220. public playEnvironmentSound(sfxPath: string, volume?: number) {
  221. this.playSound(this.environmentSoundAudioSource, sfxPath, volume, this.environmentSoundVolume, '环境音效');
  222. }
  223. public playWeaponSound(sfxPath: string, volume?: number) {
  224. this.playSound(this.weaponSoundAudioSource, sfxPath, volume, this.weaponSoundVolume, '武器音效');
  225. }
  226. private async playSound(audioSource: AudioSource, sfxPath: string, volume: number | undefined, baseVolume: number, soundType: string) {
  227. if (!audioSource) {
  228. console.warn(`[AudioManager] ${soundType}播放器未初始化`);
  229. return;
  230. }
  231. try {
  232. const cleanPath = sfxPath.replace('data/', '').replace(/\.(mp3|wav|ogg)$/i, '');
  233. const bundlePath = cleanPath;
  234. const clip = await this.bundleLoader.loadAssetFromBundle<AudioClip>('data', bundlePath, AudioClip);
  235. if (volume !== undefined) {
  236. audioSource.volume = Math.max(0, Math.min(1, volume));
  237. } else {
  238. audioSource.volume = baseVolume;
  239. }
  240. audioSource.playOneShot(clip);
  241. console.log(`[AudioManager] 播放${soundType}: ${cleanPath}`);
  242. } catch (error) {
  243. console.error(`[AudioManager] 加载${soundType}失败: ${sfxPath}`, error);
  244. }
  245. }
  246. public setMusicVolume(volume: number) {
  247. this.musicVolume = Math.max(0, Math.min(1, volume));
  248. this.updateMusicVolume();
  249. //console.log(`[AudioManager] 设置音乐音量: ${this.musicVolume}`);
  250. }
  251. public setSoundEffectVolume(volume: number) {
  252. this.soundEffectVolume = Math.max(0, Math.min(1, volume));
  253. //console.log(`[AudioManager] 设置音效音量: ${this.soundEffectVolume}`);
  254. }
  255. public setUISoundVolume(volume: number) {
  256. this.uiSoundVolume = Math.max(0, Math.min(1, volume));
  257. this.updateUISoundVolume();
  258. }
  259. public setEnemySoundVolume(volume: number) {
  260. this.enemySoundVolume = Math.max(0, Math.min(1, volume));
  261. this.updateEnemySoundVolume();
  262. }
  263. public setEnvironmentSoundVolume(volume: number) {
  264. this.environmentSoundVolume = Math.max(0, Math.min(1, volume));
  265. this.updateEnvironmentSoundVolume();
  266. }
  267. public setWeaponSoundVolume(volume: number) {
  268. this.weaponSoundVolume = Math.max(0, Math.min(1, volume));
  269. this.updateWeaponSoundVolume();
  270. }
  271. public setAllSoundVolume(volume: number) {
  272. this.setSoundEffectVolume(volume);
  273. this.setUISoundVolume(volume);
  274. this.setEnemySoundVolume(volume);
  275. this.setEnvironmentSoundVolume(volume);
  276. this.setWeaponSoundVolume(volume);
  277. }
  278. public getMusicVolume(): number {
  279. return this.musicVolume;
  280. }
  281. public getSoundEffectVolume(): number {
  282. return this.soundEffectVolume;
  283. }
  284. public getUISoundVolume(): number {
  285. return this.uiSoundVolume;
  286. }
  287. public getEnemySoundVolume(): number {
  288. return this.enemySoundVolume;
  289. }
  290. public getEnvironmentSoundVolume(): number {
  291. return this.environmentSoundVolume;
  292. }
  293. public getWeaponSoundVolume(): number {
  294. return this.weaponSoundVolume;
  295. }
  296. private updateMusicVolume() {
  297. if (this.musicAudioSource) {
  298. this.musicAudioSource.volume = this.musicVolume;
  299. }
  300. }
  301. private updateUISoundVolume() {
  302. if (this.uiSoundAudioSource) {
  303. this.uiSoundAudioSource.volume = this.uiSoundVolume;
  304. }
  305. }
  306. private updateEnemySoundVolume() {
  307. if (this.enemySoundAudioSource) {
  308. this.enemySoundAudioSource.volume = this.enemySoundVolume;
  309. }
  310. }
  311. private updateEnvironmentSoundVolume() {
  312. if (this.environmentSoundAudioSource) {
  313. this.environmentSoundAudioSource.volume = this.environmentSoundVolume;
  314. }
  315. }
  316. private updateWeaponSoundVolume() {
  317. if (this.weaponSoundAudioSource) {
  318. this.weaponSoundAudioSource.volume = this.weaponSoundVolume;
  319. }
  320. }
  321. private updateAllVolumes() {
  322. this.updateMusicVolume();
  323. this.updateUISoundVolume();
  324. this.updateEnemySoundVolume();
  325. this.updateEnvironmentSoundVolume();
  326. this.updateWeaponSoundVolume();
  327. }
  328. public muteAll() {
  329. this.setMusicVolume(0);
  330. this.setAllSoundVolume(0);
  331. }
  332. public unmuteAll() {
  333. this.setMusicVolume(0.8);
  334. this.setAllSoundVolume(0.8);
  335. }
  336. public muteAllSounds() {
  337. this.setAllSoundVolume(0);
  338. }
  339. public unmuteAllSounds() {
  340. this.setAllSoundVolume(0.8);
  341. }
  342. public isMusicPlaying(): boolean {
  343. return !!(this.musicAudioSource && this.musicAudioSource.playing);
  344. }
  345. public clearAudioCache() {
  346. console.log(`[AudioManager] 清理音频缓存,共${this.audioClipCache.size}个音效`);
  347. this.audioClipCache.clear();
  348. }
  349. public getCacheInfo(): {count: number, paths: string[]} {
  350. return { count: this.audioClipCache.size, paths: Array.from(this.audioClipCache.keys()) };
  351. }
  352. onDestroy() {
  353. this.clearAudioCache();
  354. if (AudioManager._instance === this) {
  355. AudioManager._instance = null;
  356. }
  357. }
  358. }
  359. export class Audio {
  360. static playMusic(musicPath: string, loop: boolean = true) {
  361. const manager = AudioManager.getInstance();
  362. if (manager) {
  363. manager.playMusic(musicPath, loop);
  364. }
  365. }
  366. static playSFX(sfxPath: string, volume?: number) {
  367. const manager = AudioManager.getInstance();
  368. if (manager) {
  369. manager.playSoundEffect(sfxPath, volume);
  370. }
  371. }
  372. static playUISound(sfxPath: string, volume?: number) {
  373. const manager = AudioManager.getInstance();
  374. if (manager) {
  375. manager.playUISound(sfxPath, volume);
  376. }
  377. }
  378. static playEnemySound(sfxPath: string, volume?: number) {
  379. const manager = AudioManager.getInstance();
  380. if (manager) {
  381. manager.playEnemySound(sfxPath, volume);
  382. }
  383. }
  384. static playEnvironmentSound(sfxPath: string, volume?: number) {
  385. const manager = AudioManager.getInstance();
  386. if (manager) {
  387. manager.playEnvironmentSound(sfxPath, volume);
  388. }
  389. }
  390. static playWeaponSound(sfxPath: string, volume?: number) {
  391. const manager = AudioManager.getInstance();
  392. if (manager) {
  393. manager.playWeaponSound(sfxPath, volume);
  394. }
  395. }
  396. static setMusicVolume(volume: number) {
  397. const manager = AudioManager.getInstance();
  398. if (manager) {
  399. manager.setMusicVolume(volume);
  400. }
  401. }
  402. static setSFXVolume(volume: number) {
  403. const manager = AudioManager.getInstance();
  404. if (manager) {
  405. manager.setSoundEffectVolume(volume);
  406. }
  407. }
  408. static setUISoundVolume(volume: number) {
  409. const manager = AudioManager.getInstance();
  410. if (manager) {
  411. manager.setUISoundVolume(volume);
  412. }
  413. }
  414. static setEnemySoundVolume(volume: number) {
  415. const manager = AudioManager.getInstance();
  416. if (manager) {
  417. manager.setEnemySoundVolume(volume);
  418. }
  419. }
  420. static setEnvironmentSoundVolume(volume: number) {
  421. const manager = AudioManager.getInstance();
  422. if (manager) {
  423. manager.setEnvironmentSoundVolume(volume);
  424. }
  425. }
  426. static setWeaponSoundVolume(volume: number) {
  427. const manager = AudioManager.getInstance();
  428. if (manager) {
  429. manager.setWeaponSoundVolume(volume);
  430. }
  431. }
  432. static setAllSoundVolume(volume: number) {
  433. const manager = AudioManager.getInstance();
  434. if (manager) {
  435. manager.setAllSoundVolume(volume);
  436. }
  437. }
  438. static stopMusic() {
  439. const manager = AudioManager.getInstance();
  440. if (manager) {
  441. manager.stopMusic();
  442. }
  443. }
  444. static pauseMusic() {
  445. const manager = AudioManager.getInstance();
  446. if (manager) {
  447. manager.pauseMusic();
  448. }
  449. }
  450. static resumeMusic() {
  451. const manager = AudioManager.getInstance();
  452. if (manager) {
  453. manager.resumeMusic();
  454. }
  455. }
  456. static muteAll() {
  457. const manager = AudioManager.getInstance();
  458. if (manager) {
  459. manager.muteAll();
  460. }
  461. }
  462. static unmuteAll() {
  463. const manager = AudioManager.getInstance();
  464. if (manager) {
  465. manager.unmuteAll();
  466. }
  467. }
  468. static muteAllSounds() {
  469. const manager = AudioManager.getInstance();
  470. if (manager) {
  471. manager.muteAllSounds();
  472. }
  473. }
  474. static unmuteAllSounds() {
  475. const manager = AudioManager.getInstance();
  476. if (manager) {
  477. manager.unmuteAllSounds();
  478. }
  479. }
  480. static clearAudioCache() {
  481. const manager = AudioManager.getInstance();
  482. if (manager) {
  483. manager.clearAudioCache();
  484. }
  485. }
  486. static getCacheInfo(): {count: number, paths: string[]} {
  487. const manager = AudioManager.getInstance();
  488. if (manager) {
  489. return manager.getCacheInfo();
  490. }
  491. return { count: 0, paths: [] };
  492. }
  493. static ensureManager(): AudioManager | null {
  494. let manager = AudioManager.getInstance();
  495. if (manager) return manager;
  496. try {
  497. const canvas = find('Canvas') as Node | null;
  498. const sceneRoot: any = director.getScene();
  499. const parent: Node | null = canvas || (sceneRoot as Node | null);
  500. if (!parent) {
  501. console.warn('[Audio] 场景未准备好,无法创建AudioManager');
  502. return null;
  503. }
  504. // 先尝试在场景中查找已存在的 AudioManager 组件
  505. if (canvas && typeof (canvas as any).getComponentInChildren === 'function') {
  506. const existing = (canvas as any).getComponentInChildren(AudioManager);
  507. if (existing) {
  508. return existing;
  509. }
  510. }
  511. if (sceneRoot && typeof sceneRoot.getComponentInChildren === 'function') {
  512. const existingInScene = sceneRoot.getComponentInChildren(AudioManager);
  513. if (existingInScene) {
  514. return existingInScene;
  515. }
  516. }
  517. // 查找名为 AudioManager 的节点,复用其组件
  518. let node = parent.getChildByName && parent.getChildByName('AudioManager');
  519. if (!node) {
  520. node = new Node('AudioManager');
  521. parent.addChild(node as Node);
  522. }
  523. const reused = (node as Node).getComponent(AudioManager);
  524. manager = reused ? reused : (node as Node).addComponent(AudioManager);
  525. return manager;
  526. } catch (e) {
  527. console.error('[Audio] 创建AudioManager失败:', e);
  528. return null;
  529. }
  530. }
  531. static updateBGMByTopUI(): void {
  532. try {
  533. const manager = Audio.ensureManager();
  534. if (!manager) {
  535. console.warn('[Audio] AudioManager未初始化,稍后重试BGM切换');
  536. return;
  537. }
  538. const gm = GameManager.getInstance();
  539. let isInGame = false;
  540. if (gm && typeof gm.isInGame === 'function') {
  541. isInGame = gm.isInGame();
  542. } else {
  543. const gameUI = find('Canvas/GameLevelUI');
  544. isInGame = !!(gameUI && (gameUI as Node).activeInHierarchy);
  545. }
  546. // 保持用户设置的音量,不重置为固定值
  547. Audio.setMusicVolume(manager.getMusicVolume());
  548. // 仅当目标曲目与当前不同或未播放时才切换;
  549. // playMusic 内部已防重,若同曲且正在播放会直接忽略。
  550. const targetPath = isInGame ? 'data/弹球音效/fight bgm' : 'data/弹球音效/ui bgm';
  551. Audio.playMusic(targetPath, true);
  552. console.log(isInGame ? '[Audio] 维持/切换到游戏战斗音乐' : '[Audio] 维持/切换到主界面背景音乐');
  553. } catch (err) {
  554. console.error('[Audio] updateBGMByTopUI 失败:', err);
  555. }
  556. }
  557. }