PlaySoundManager.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // 音频管理类 单例模式
  2. // 用法:playSoundManager.getInstance().playSound("soundName",1,false);
  3. // 1.第一个参数是音频名称,2.第二个参数是音量,3.第三个参数是是否循环
  4. const { ccclass, property } = cc._decorator;
  5. @ccclass
  6. export default class PlaySoundManager extends cc.Component {
  7. // 单例
  8. private static _instance: PlaySoundManager = null;
  9. public static getInstance(): PlaySoundManager {
  10. if (!PlaySoundManager._instance) {
  11. PlaySoundManager._instance = new PlaySoundManager();
  12. }
  13. return PlaySoundManager._instance;
  14. }
  15. // 加载音频
  16. public loadSound(soundName: string, callback: Function): void {
  17. cc.loader.loadRes(
  18. soundName,
  19. cc.AudioClip,
  20. function (err, clip) {
  21. if (err) {
  22. cc.error(err.message || err);
  23. return;
  24. }
  25. if (callback) callback(clip);
  26. }.bind(this)
  27. );
  28. }
  29. /**
  30. * 播放音效
  31. *
  32. * @param {cc.AudioClip} soundClip
  33. * @param {boolean} [loop=true]
  34. * @param {number} volume
  35. * @memberof PlaySoundManager
  36. */
  37. public playSound(soundClip: cc.AudioClip, loop: boolean = true, volume?: number): void {
  38. cc.audioEngine.playEffect(soundClip, loop);
  39. }
  40. /**
  41. * 停止所有音效
  42. *
  43. * @memberof PlaySoundManager
  44. */
  45. public stopAllSound(): void {
  46. cc.audioEngine.stopAllEffects();
  47. }
  48. }