AudioManage.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { _decorator, AudioClip, AudioSource, Component, Node, resources } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('AudioManage')
  4. export class AudioManage extends Component {
  5. private static _instance: AudioManage;
  6. private static _audioSource?: AudioSource;
  7. static get instance() {
  8. if (this._instance) {
  9. return this._instance;
  10. }
  11. this._instance = new AudioManage();
  12. return this._instance;
  13. }
  14. protected onLoad(): void {
  15. this.init();
  16. }
  17. init() {
  18. AudioManage._audioSource = this.node.getComponent(AudioSource);
  19. }
  20. //播放音乐
  21. playMusic(loop: boolean = true) {
  22. const audioSource = AudioManage._audioSource!;
  23. audioSource.loop = loop;
  24. if (!audioSource.playing) {
  25. audioSource.play();
  26. }
  27. }
  28. //暂停音乐
  29. pauseMusic() {
  30. const audioSource = AudioManage._audioSource!;
  31. if (audioSource.playing) {
  32. audioSource.stop();
  33. }
  34. }
  35. /**
  36. * 播放音效
  37. * @param {String} name 音效名称
  38. * @param {Number} volumeScale 播放音量倍数
  39. */
  40. playSound(name: string, volumeScale: number = 1) {
  41. const audioSource = AudioManage._audioSource!;
  42. resources.load(name, AudioClip, (err: any, ac) => {
  43. audioSource.playOneShot(ac, volumeScale);
  44. });
  45. }
  46. setBgVolume(value: number) {
  47. const audioSource = AudioManage._audioSource!;
  48. audioSource.volume = value;
  49. }
  50. }