AudioMusic.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { AudioClip, AudioSource, error, _decorator } from 'cc';
  2. import { resLoader } from '../res/ResLoader';
  3. const { ccclass, menu } = _decorator;
  4. export class AudioMusic extends AudioSource {
  5. onComplete: Function = null;
  6. private _progress: number = 0;
  7. private _url: string = null;
  8. private _is_play: boolean = false;
  9. /**
  10. * 设置音乐当前播放进度
  11. * @param progress 进度百分比(0~1)
  12. */
  13. get progress() {
  14. this._progress = this.currentTime / this.duration;
  15. return this._progress;
  16. }
  17. set progress(value: number) {
  18. this._progress = value;
  19. this.currentTime = value * this.duration;
  20. }
  21. load(bundle: string, url: string, callback?: Function,loop: boolean = true) {
  22. resLoader.load(bundle, url, AudioClip, (error: Error, clip: AudioClip) => {
  23. if (error) {
  24. console.error(error);
  25. } else {
  26. if (this.playing) {
  27. this._is_play = false;
  28. this.stop();
  29. // resLoader.release(this._url!, bundle);
  30. }
  31. this.clip = clip;
  32. this.currentTime = 0;
  33. this.loop = loop;
  34. this.play();
  35. callback && callback();
  36. this._url = url;
  37. }
  38. });
  39. }
  40. update() {
  41. (this.currentTime > 0) && (this._is_play = true);
  42. if (this._is_play && this.playing == false) {
  43. this._is_play = false;
  44. this.onComplete && this.onComplete();
  45. }
  46. }
  47. }