CocosCreator 音效管理

1 创建音效管理类 SoundMgr.ts

 const {ccclass, property} = cc._decorator;

@ccclass
export default class SoundMgr {
    sound_path:string = 'Sound/';
    sounds:{[key:number]:any} = {};
    enabled:boolean = true;
    music:string = '';
    protected static instance:SoundMgr;
    public static getInstance():SoundMgr
    {
        if(!this.instance)
        {
            this.instance = new SoundMgr();
        }
        return this.instance;
    }

    addSound(key:string, clip:cc.AudioClip)
    {
        this.sounds[key] = clip;
    }

    playFx(fxName:string)
    {
        if(!this.enabled) return;
        cc.audioEngine.playEffect(this.sounds[fxName], false);
    }

    playMusic(musicName:string)
    {
        this.music = musicName;
        if(!this.enabled) return;
        cc.audioEngine.playMusic(this.sounds[musicName], true);
    }

    stopMusic()
    {
        cc.audioEngine.stopMusic();
    }
    
    setEnabled(enabled:boolean)
    {
        this.enabled = enabled;
        if(this.enabled)
        {
            this.playMusic(this.music);
        }
        else
        {
            cc.audioEngine.stopAll();
        }
    }

    getEnable()
    {
        return this.enabled;
    }
}

2  在初始化的时候加载音频资源

loadSounds()
    {
        cc.loader.loadResDir('Sounds', cc.AudioClip, function(err, clips)
        {
            for(let i=0; i

3 播放

SoundMgr.getInstance().playFx('score');

 

你可能感兴趣的:(Creator)