二、 Cocos Creator 音效管理组件封装
1.创建音效管理类 SoundMgr.ts
const { ccclass, property } = cc._decorator; @ccclass exportdefaultclassSoundMgr { sound_path: string = 'res/sounds/'; // sound 中保存的是音乐的名称和音频对象的 key-value 键值对 sounds: { [key: string]: any } = {}; enabled: boolean = true; music: string = ''; // 单例模式 protectedstatic instance: SoundMgr; publicstatic getInstance(): SoundMgr { if (!this.instance) { this.instance = newSoundMgr(); } returnthis.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() { returnthis.enabled; } }
2. 在初始化的时候加载音频资源
通过 Cocos Creator 可视化编辑工具,我们设置游戏场景和资源如下:
因为 sounds 我们是通过代码动态加载,故我们将保存所有声音文件的 sounds 文件夹放 到 resources 文件夹内(如上图)。