首页 > 脚本 > 网络编程 > CocosCreator开发中游戏音频相关的处理教程说明,游戏开发中如何使用CocosCreator进行音效处理

CocosCreator开发中游戏音频相关的处理教程说明,游戏开发中如何使用CocosCreator进行音效处理

来源:整理 时间:2022-03-07 16:30:47 编辑:飘云 手机版

二、 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 文件夹内(如上图)。

文章TAG:Cocos音效cocos音频CocosCreator

最近更新

网络编程最新文章

脚本排行榜推荐