AudioManage.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. if(ac){
  44. audioSource.playOneShot(ac, volumeScale);
  45. }
  46. });
  47. }
  48. setBgVolume(value: number) {
  49. const audioSource = AudioManage._audioSource!;
  50. audioSource.volume = value;
  51. }
  52. }