audioManager.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { _decorator, AudioClip, AudioSource, Component, Node } from 'cc';
  2. import { ResourceUtil } from './ResourceUtil';
  3. const { ccclass, property } = _decorator;
  4. @ccclass('audioManager')
  5. export class audioManager extends Component {
  6. public arrSound: any = [];
  7. public audios: any = {};
  8. public musicVolume: number = 0.8;
  9. public soundVolume: number = 1;
  10. public playMusic(clip:AudioClip){
  11. if(clip!=null){
  12. this.getSound().clip = null;
  13. this.getSound().loop = true;
  14. this.getSound().clip = clip;
  15. this.getSound().play()
  16. }
  17. }
  18. public playSound(path:string){
  19. if(path.length<=0){
  20. return
  21. }
  22. let loop:boolean = false
  23. ResourceUtil.loadRes(path, AudioClip, (err: any, clip: any)=> {
  24. let tmp = {} as any;
  25. tmp.clip = clip;
  26. tmp.loop = loop;
  27. tmp.isMusic = false;
  28. this.arrSound.push(tmp);
  29. if (loop) {
  30. this.audios[path] = tmp;
  31. clip.setLoop(loop);
  32. }
  33. clip.setVolume(this.soundVolume);
  34. clip.playOneShot();
  35. clip.once('ended', ()=>{
  36. ResourceUtil.remove(this.arrSound, (obj: any)=>{
  37. return obj.clip === tmp.clip;
  38. });
  39. })
  40. });
  41. }
  42. getSound(){
  43. if(this.node.getComponent(AudioSource)!=null){
  44. return this.node.getComponent(AudioSource)
  45. }
  46. return this.node.addComponent(AudioSource)
  47. }
  48. }