AudioMgr.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { _decorator, AudioClip, AudioSource, Component, Game, game } from 'cc'
  2. import { Debug } from '../util/Debug'
  3. import { ResMgr } from './ResMgr'
  4. import { Setting } from '../Setting'
  5. const { ccclass, property, requireComponent } = _decorator
  6. const Tag: string = 'AudioMgr'
  7. //需要手动拖放到场景中
  8. @ccclass('Manager/AudioMgr')
  9. @requireComponent(AudioSource)
  10. export class AudioMgr extends Component {
  11. private static audio: AudioSource
  12. public static get Audio(): AudioSource {
  13. return this.audio
  14. }
  15. private static curBgm: string = null
  16. public static get CurBgm(): string {
  17. return this.curBgm
  18. }
  19. public static bundleName: string = 'audio'
  20. protected onLoad(): void {
  21. globalThis.AudioMgr = AudioMgr
  22. AudioMgr.audio = this.getComponent(AudioSource)
  23. game.on(Game.EVENT_HIDE, this.onHide, this)
  24. game.on(Game.EVENT_SHOW, this.onShow, this)
  25. }
  26. protected onHide(): void {
  27. AudioMgr.pauseBgm()
  28. Debug.Log(Tag, '进入后台')
  29. }
  30. protected onShow(): void {
  31. AudioMgr.resumeBgm()
  32. Debug.Log(Tag, '回到前台')
  33. }
  34. public static playBgm(bgm?: string, volume: number = 1, loop: boolean = true): void {
  35. if (bgm) this.curBgm = bgm
  36. if (!Setting.BgmEnabled) return
  37. let clip: AudioClip = ResMgr.getRes(this.bundleName, this.curBgm)
  38. if (!clip) return
  39. this.audio.stop()
  40. this.audio.clip = clip
  41. this.audio.loop = loop
  42. this.audio.volume = volume
  43. this.audio.play()
  44. }
  45. public static pauseBgm(): void {
  46. Setting.BgmEnabled && this.audio.pause()
  47. }
  48. public static resumeBgm(): void {
  49. Setting.BgmEnabled && this.audio.play()
  50. }
  51. public static stopBgm(): void {
  52. this.audio.stop()
  53. this.audio.clip = null
  54. }
  55. public static playSfx(sfxName: string, volumeScale: number = 1): void {
  56. if (!Setting.SfxEnabled) return
  57. let clip: AudioClip = ResMgr.getRes<AudioClip>(this.bundleName, sfxName)
  58. if (!clip) return
  59. this.audio.playOneShot(clip, volumeScale)
  60. }
  61. }