SoundManager.ts 1.98 KB
import { SoundName } from "../Global";
import { SaveDataManager } from "./SaveDataManager";

export class SoundManager {

    private _cdMap: Map<string, number> = new Map<string, number>();

    private static _ins: SoundManager = null;
    static get ins(): SoundManager {
        if (this._ins == null) {
            this._ins = new SoundManager();
        }

        return this._ins;
    }

    update(dt: number) {

        this._cdMap.forEach((value, key, map) => {

            if (value > 0) {
                value -= dt;
            }

            if (value < 0) {
                value = 0;
            }

            map.set(key, value);

        }, this);
    }

    playEffect(clipName: string) {

        if (!SaveDataManager.ins.runtimeData.SEMute) {


            if (clipName == SoundName.HIT || clipName == SoundName.BREAK) {
                //检查cd 
                if (this._cdMap.has(clipName) && this._cdMap.get(clipName) > 0) {
                    return;
                }
                else {

                    let cd = (clipName == SoundName.HIT ? 0.1 : 0.6);
                    this._cdMap.set(clipName, cd);
                }
            }

            let clip = cc.resources.get('soundEffect/' + clipName, cc.AudioClip) as cc.AudioClip;
            if (clip) {
                cc.audioEngine.playEffect(clip, false);
            }
            else {
                cc.warn('can not find audio clip:', clipName);
            }
        }
    }

    playMusic() {

        if (!SaveDataManager.ins.runtimeData.musicMute) {
            let clip = cc.resources.get('soundEffect/' + SoundName.BGM, cc.AudioClip) as cc.AudioClip;
            if (clip && !cc.audioEngine.isMusicPlaying()) {
                cc.audioEngine.playMusic(clip, true);
            }
            // else {
            //     cc.warn('can not find audio clip: BGM');
            // }
        }
    }

    stopMusic() {
        if (cc.audioEngine.isMusicPlaying()) {
            cc.audioEngine.stopMusic();
        }
    }
}