AudioManager.ts 21 KB

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