AudioManager.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { _decorator, AudioClip, AudioSource, assert } from 'cc';
  2. import { GlobalData } from '../GlobalData';
  3. import { AudioClipNames } from '../GlobalTypes';
  4. const { ccclass, property } = _decorator;
  5. @ccclass('AudioManager')
  6. export class AudioManager {
  7. private audioSource: AudioSource = null;
  8. private soundOn: boolean = true
  9. clips: {[props:string]:AudioClip} = {}
  10. private static _instance: AudioManager;
  11. public static get instance () {
  12. if (this._instance) {
  13. return this._instance;
  14. }
  15. this._instance = new AudioManager();
  16. return this._instance;
  17. }
  18. init(audioSource: AudioSource){
  19. this.audioSource = audioSource
  20. this.getSoundConfig()
  21. if (this.soundOn){
  22. this.play()
  23. }else {
  24. this.pause()
  25. }
  26. }
  27. getSoundConfig(){
  28. this.soundOn = GlobalData.instance.getConfigData("audioconfig")
  29. if (this.soundOn === null){
  30. this.soundOn = true
  31. }
  32. return this.soundOn
  33. }
  34. setSoundConfig(soundOn: boolean) {
  35. this.soundOn = soundOn
  36. if (this.soundOn){
  37. this.play()
  38. }else {
  39. this.pause()
  40. }
  41. GlobalData.instance.setConfigData("audioconfig", this.soundOn)
  42. }
  43. play () {
  44. if (!this.soundOn) return
  45. // 播放音乐
  46. this.audioSource.play();
  47. }
  48. pause () {
  49. // 暂停音乐
  50. this.audioSource.pause();
  51. }
  52. async playBgm (clipName: AudioClipNames) {
  53. if (!this.soundOn) return
  54. this.audioSource.stop()
  55. this.audioSource.clip = this.clips[AudioClipNames[clipName]]
  56. this.audioSource.play();
  57. }
  58. playOneShot (clipName: AudioClipNames, volume: number = 1) {
  59. if (!this.soundOn) return
  60. this.audioSource.playOneShot(this.clips[AudioClipNames[clipName]], volume);
  61. }
  62. }