AudioManager.ts 21 KB

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