AudioManage.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. /**
  51. * 播放音效带回调
  52. * @param name
  53. * @param volumeScale
  54. * @param onEnd
  55. */
  56. playSoundCallback(name: string, volumeScale: number = 1, isLoop: boolean = false, onEnd?: Function, callback?: any) {
  57. const audioSource = AudioManage._audioSource!;
  58. audioSource.node.off(AudioSource.EventType.ENDED)
  59. audioSource.node.on(AudioSource.EventType.ENDED, onEnd, callback)
  60. audioSource.loop = isLoop
  61. // audioSource.volume = volumeScale
  62. resources.load(name, AudioClip, (err: any, ac) => {
  63. if (err) {
  64. console.log(err);
  65. } else {
  66. audioSource.clip = ac
  67. audioSource.play();
  68. }
  69. });
  70. }
  71. }