
export default class AudioM {
    constructor() { };

    static _instance;
    static getIns(): AudioM {
        if (!this._instance) {
            this._instance = new AudioM();
        }

        return this._instance;
    }

    canPlayMusic = true;

    playingEffect;
    playClose(str = '') {
        this.loadAudioRes('common_close' + str).then((clip: any) => {
            if (!this.playingEffect) this.playingEffect = {};
            this.playingEffect[clip.name] = { time: new Date().getTime() };
            var audioID = cc.audioEngine.playEffect(clip, false);

            let self = this;
            cc.audioEngine.setFinishCallback(audioID, (data) => {
                if (self.playingEffect[clip.name])
                    delete self.playingEffect[clip.name];
                cc.audioEngine.setFinishCallback(audioID, null);
            })
        })
    }

    playClick(str = '') {
        this.loadAudioRes('common_click' + str).then((clip: any) => {
            if (!this.playingEffect) this.playingEffect = {};
            this.playingEffect[clip.name] = { time: new Date().getTime() };
            var audioID = cc.audioEngine.playEffect(clip, false);

            let self = this;
            cc.audioEngine.setFinishCallback(audioID, (data) => {
                if (self.playingEffect[clip.name])
                    delete self.playingEffect[clip.name];
                cc.audioEngine.setFinishCallback(audioID, null);
            })
        })
    }

    playMusic(name) {
        this.loadAudioRes(name).then((clip: any) => {
            cc.audioEngine.playMusic(clip, true);
        });
    }

    loadAudioRes(audioUrl) {
        return new Promise((resolve, reject) => {
            cc.resources.load(audioUrl, cc.AudioClip, function (err, data) {
                if (err && !data) return cc.warn('loading loadRes error-> ' + audioUrl);
                resolve(data);
            });
        });
    }

}