AudioManage.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import {_decorator, AudioClip, AudioSource, Component, Node, resources} from 'cc';
  2. import {LoadUtils} from '../../script/utils/LoadUtils';
  3. const {ccclass, property} = _decorator;
  4. @ccclass('AudioManage')
  5. export class AudioManage extends Component {
  6. private static _instance: AudioManage;
  7. private static _audioSource?: AudioSource;
  8. static get instance() {
  9. if (this._instance) {
  10. return this._instance;
  11. }
  12. this._instance = new AudioManage();
  13. return this._instance;
  14. }
  15. protected onLoad(): void {
  16. this.init();
  17. }
  18. init() {
  19. AudioManage._audioSource = this.node.getComponent(AudioSource);
  20. }
  21. //播放音乐
  22. playMusic(loop: boolean = true) {
  23. const audioSource = AudioManage._audioSource!;
  24. audioSource.loop = loop;
  25. if (!audioSource.playing) {
  26. audioSource.play();
  27. }
  28. }
  29. //暂停音乐
  30. pauseMusic() {
  31. const audioSource = AudioManage._audioSource!;
  32. if (audioSource.playing) {
  33. audioSource.stop();
  34. }
  35. }
  36. /**
  37. * 播放音效
  38. * @param {String} name 音效名称
  39. * @param {Number} volumeScale 播放音量倍数
  40. */
  41. playSound(name: string, volumeScale: number = 1) {
  42. const audioSource = AudioManage._audioSource!;
  43. resources.load(name, AudioClip, (err: any, ac) => {
  44. audioSource.playOneShot(ac, volumeScale);
  45. });
  46. }
  47. setBgVolume(value: number) {
  48. const audioSource = AudioManage._audioSource!;
  49. audioSource.volume = value;
  50. }
  51. /**
  52. * 播放音效带回调
  53. * @param name
  54. * @param volumeScale
  55. * @param onEnd
  56. */
  57. playSoundCallback(name: string, volumeScale: number = 1, isLoop: boolean = false, onEnd?: Function, callback?: any) {
  58. const audioSource = AudioManage._audioSource!;
  59. audioSource.node.off(AudioSource.EventType.ENDED)
  60. audioSource.node.on(AudioSource.EventType.ENDED, onEnd, callback)
  61. audioSource.loop = isLoop
  62. // audioSource.volume = volumeScale
  63. // resources.load(name, AudioClip, (err: any, ac) => {
  64. // if (err) {
  65. // console.log(err);
  66. // } else {
  67. // audioSource.clip = ac
  68. // audioSource.play();
  69. // }
  70. // });
  71. LoadUtils.loadBundleRes("distance", "resources/" + name, (ac) => {
  72. audioSource.clip = ac
  73. audioSource.play();
  74. }, null, AudioClip)
  75. }
  76. }