Sound.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { AudioClip, Component, SystemEventType, _decorator } from "cc";
  2. const { ccclass, property } = _decorator;
  3. /**
  4. * 声音组件
  5. * @author 袁浩
  6. */
  7. @ccclass("Sound")
  8. export class Sound extends Component {
  9. @property({ tooltip: "点击后播放的声音", type: [AudioClip] })
  10. public clips: AudioClip[] = [];
  11. @property({ visible: false })
  12. private _volume: number = 1;
  13. @property({ tooltip: "音量", min: 0, max: 1, step: 0.1 })
  14. public get volume(): number {
  15. return this._volume;
  16. }
  17. public set volume(value: number) {
  18. for (let i = 0; i < this.clips.length; i++) {
  19. const clip = this.clips[i];
  20. clip.setVolume(value);
  21. }
  22. this._volume = value;
  23. }
  24. @property({ tooltip: "音量是否受全局影响" })
  25. public useGlobalVolume: boolean = true;
  26. @property({ tooltip: "是否在声音组件运行时自动播放" })
  27. public playOnLoad: boolean = true;
  28. @property({ tooltip: "是否在触摸节点时播放" })
  29. public playOnTouch: boolean = false;
  30. @property({ tooltip: "播放时是否不覆盖前一个声音" })
  31. public oneShot: boolean = true;
  32. @property({
  33. tooltip: "是否循环播放", visible() {
  34. return !this.oneShot;
  35. }
  36. })
  37. public loop: boolean = false;
  38. /**
  39. * Sound组件全局音量系数
  40. */
  41. public static volumeScale: number = 1;
  42. start() {
  43. this.node.on(SystemEventType.TOUCH_END, this.onTouchEnd, this);
  44. this.playOnLoad && this.play();
  45. }
  46. private onTouchEnd() {
  47. this.playOnTouch && this.play();
  48. }
  49. public play(index: number = 0) {
  50. var volume = this.volume * (this.useGlobalVolume ? Sound.volumeScale : 1);
  51. this.clips[index].setLoop(this.loop);
  52. if (this.oneShot) {
  53. this.clips[index].playOneShot(volume);
  54. }
  55. else {
  56. for (let i = 0; i < this.clips.length; i++) {
  57. const clip = this.clips[i];
  58. if (i != index) {
  59. clip.stop();
  60. }
  61. }
  62. this.clips[index].setVolume(volume);
  63. this.clips[index].play();
  64. }
  65. }
  66. public stop() {
  67. this.clips[0].stop();
  68. }
  69. }