| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- import { AudioClip, Component, SystemEventType, _decorator } from "cc";
- const { ccclass, property } = _decorator;
- /**
- * 声音组件
- * @author 袁浩
- */
- @ccclass("Sound")
- export class Sound extends Component {
- @property({ tooltip: "点击后播放的声音", type: [AudioClip] })
- public clips: AudioClip[] = [];
- @property({ visible: false })
- private _volume: number = 1;
- @property({ tooltip: "音量", min: 0, max: 1, step: 0.1 })
- public get volume(): number {
- return this._volume;
- }
- public set volume(value: number) {
- for (let i = 0; i < this.clips.length; i++) {
- const clip = this.clips[i];
- clip.setVolume(value);
- }
- this._volume = value;
- }
- @property({ tooltip: "音量是否受全局影响" })
- public useGlobalVolume: boolean = true;
- @property({ tooltip: "是否在声音组件运行时自动播放" })
- public playOnLoad: boolean = true;
- @property({ tooltip: "是否在触摸节点时播放" })
- public playOnTouch: boolean = false;
- @property({ tooltip: "播放时是否不覆盖前一个声音" })
- public oneShot: boolean = true;
- @property({
- tooltip: "是否循环播放", visible() {
- return !this.oneShot;
- }
- })
- public loop: boolean = false;
- /**
- * Sound组件全局音量系数
- */
- public static volumeScale: number = 1;
- start() {
- this.node.on(SystemEventType.TOUCH_END, this.onTouchEnd, this);
- this.playOnLoad && this.play();
- }
- private onTouchEnd() {
- this.playOnTouch && this.play();
- }
- public play(index: number = 0) {
- var volume = this.volume * (this.useGlobalVolume ? Sound.volumeScale : 1);
- this.clips[index].setLoop(this.loop);
- if (this.oneShot) {
- this.clips[index].playOneShot(volume);
- }
- else {
- for (let i = 0; i < this.clips.length; i++) {
- const clip = this.clips[i];
- if (i != index) {
- clip.stop();
- }
- }
- this.clips[index].setVolume(volume);
- this.clips[index].play();
- }
- }
- public stop() {
- this.clips[0].stop();
- }
- }
|