How to use CocosCreator for sound processing in game development

How to use CocosCreator for sound processing in game development

In game development, we often need to use sound effects to create a game atmosphere, so this article summarizes the encapsulation and use of sound effect components in Cocos Creator game development.

1. Basics of audio playback in Cocos Creator

1. Basics

【1】AudioSource component official documentation: http://docs.cocos.com/creator/manual/zh/audio/audio.html

【2】cc.audioEngine official documentation: http://docs.cocos.com/creator/manual/zh/audio/audio.html

Cocos Creator provides two audio playback methods. AudioEngine and AudioSource can both play audio. The difference between them is that AudioSource is a component that can be added to the scene and set by the editor. AudioEngine is a pure API provided by the engine and can only be called in scripts.

Common points: They are essentially processing AudioClip audio resources, and need to mount components in the Cocos Creator editor.

I personally recommend using this to replace the AudioSource component to play sound. The interface is complete and the test is effective. You can encapsulate a script similar to the AudioSource component to use it.

Method 1: Use AudioSource component to play

Create an empty node and add another component to it-> AudioSource

Preset AudioSource in the script, and improve the script's external interface according to actual needs, as follows

cc.Class({

	properties:

		audioSource: {

			type: cc.AudioSource,
			default: null

		},
	},
	play() {

		this.audioSource.play();

	},
	pause() {

		this.audioSource.pause();

	},
});

Method 2: Use AudioEngine to play

Define an audioClip resource object in the script, as shown in the properties object in the following example.

Directly use cc.audioEngine.play(audio, loop, volume); to play. As shown in the onLoad example below.

cc.Class({

	properties:

		audio:

			default: null,
			type: cc.AudioClip

		}

	},
	onLoad() {

		this.current = cc.audioEngine.play(this.audio, false, 1);

	},
	onDestroy() {

		cc.audioEngine.stop(this.current);

	}

});

When the AudioEngine is playing, it should be noted that a complete AudioClip object (not a URL) is passed in. Therefore, we do not recommend directly filling in the audio URL in the play interface. Instead, we hope that you define an AudioClip first, and then drag the audio into the editor.

2. Common methods

【1】Component AudioSource

play ( ) Plays an audio clip.

stop ( ) Stops the current audio clip.

pause ( ) Pauses the current audio clip.

resume ( ) Resume playback.

【2】Sound system cc.audioEngine

// Background music, loop

cc.audioEngine.playMusic(source);

cc.audioEngine.stopMusic(source);

// Short sound effect

cc.audioEngine.playEffect(source);

cc.audioEngine.stopEffect(source);

The first method above has many bugs in the native platform, so our games all use the second method to play sounds.

2. Cocos Creator Sound Effect Management Component Packaging

1. Create the sound management class SoundMgr.ts

const {
	ccclass,
	property
} = cc._decorator;

@ccclass

exportdefaultclassSoundMgr {

	sound_path: string = 'res/sounds/';

	// sound stores the name of the music and the key-value pair of the audio object sounds: {
		[key: string]: any
	} = {};

	enabled: boolean = true;

	music: string = '';

	// Singleton mode protectedstatic instance: SoundMgr;

	public static getInstance(): SoundMgr {

		if (!this.instance) {

			this.instance = newSoundMgr();

		}

		returnthis.instance;

	}

	// Add sound resource 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. Load audio resources during initialization

Using the Cocos Creator visual editing tool, we set up the game scene and resources as follows:

Because we load sounds dynamically through code, we put the sounds folder that stores all sound files into the resources folder (as shown above).

Then, create GameMgr.ts and mount it to the Canvas node.

onst
	ccclass,
	property
} = cc._decorator;

importSoundMgrfrom "SoundMgr";

@ccclass

exportdefaultclassGameMgrextends cc.Component {

	loadSounds() {

		// Note that resources dynamically loaded through code must be placed in the resources folder cc.loader.loadResDir('sounds', cc.AudioClip, function(err, clips) {

			console.log("load clips:", clips);

			if (err) {

				console.log("err:", err);

			}

			for (let i = 0; i

				SoundMgr.getInstance().addSound(clips[i].name, clips[i]);

			}

		});

	}

	onLoad() {

		this.loadSounds();

		console.log("sounds:", SoundMgr.getInstance().sounds);

	}

	onPlayClick() {

		console.log("play");

		SoundMgr.getInstance().playMusic('spring_music');

	}

	onPauseClick() {

		console.log("pause");

		SoundMgr.getInstance().stopMusic();

	}

}

In the onLoad method of the GameMgr custom component, call loadSounds to load all the sound resources needed in the game. At the same time, the play and pause interface methods onPlayClick and onPauseClick are provided in GameMgr.ts.

Called by the play and pause buttons.

3. Play and Pause Calls

4. Run the test

All sound resources are loaded successfully, and the test passes when the play and pause buttons are clicked.

3. Notes

Note: If all audio playback related settings are completed, but no sound can be heard when previewing or running on some browsers, it may be due to browser compatibility issues. For example, Chrome has disabled automatic playback of WebAudio, and audio is loaded and played using Web Audio by default. In this case, the user needs to select the audio resource in the Resource Manager and then change the audio loading mode to DOM Audio in the Property Inspector to play it normally on the browser.

The above is the details of how to use CocosCreator for sound processing in game development. For more information about CocosCreator sound processing, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Cocos creator Touch event application (touch to select multiple child nodes example)
  • How to add touch events using cocos2d in iOS development
  • Cocos2d-x touch event example
  • Detailed explanation of CocosCreator optimization DrawCall
  • CocosCreator implements skill cooling effect
  • Detailed explanation of cocoscreater prefab
  • How to use resident nodes for layer management in CocosCreator
  • CocosCreator ScrollView optimization series: frame loading
  • Detailed explanation of how CocosCreator system events are generated and triggered

<<:  How to add Nginx to system services in CentOS7

>>:  Solution to the initialization error when installing mysql5.7 from rpm package in centos6.5

Recommend

Example of downloading files with vue+django

Table of contents 1. Overview 2. Django Project 3...

Vue uses Baidu Maps to realize city positioning

This article shares the specific code of Vue usin...

ElementUI implements cascading selector

This article example shares the specific code of ...

Usage instructions for the docker create command

The docker create command can create a container ...

Minimalistic website design examples

Web Application Class 1. DownForEveryoneOrJustMe ...

Examples of importing and exporting MySQL table data

This article describes the import and export oper...

Detailed tutorial on installing Protobuf 3 on Ubuntu

When to install If you use the protoc command and...

Unzipped version of MYSQL installation and encountered errors and solutions

1 Installation Download the corresponding unzippe...

Detailed View of Hidden Columns in MySQL

Table of contents 1. Primary key exists 2. No pri...

Tutorial diagram of installing TomCat in Windows 10

Install TomCat on Windows This article will intro...

Why MySQL can ignore time zone issues when using timestamp?

I have always wondered why the MySQL database tim...

Teach you how to install mysql database on Mac

Download MySQL for Mac: https://downloads.mysql.c...

Case analysis of several MySQL update operations

Table of contents Case Study Update account balan...