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<clips.length; i++)
            {
                SoundMgr.getInstance().addSound(clips[i].name, clips[i]);
            }
        });
    }

3 播放

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

 

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值