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

Implementation of Nginx Intranet Standalone Reverse Proxy

Table of contents 1 Nginx Installation 2 Configur...

Detailed explanation of mysql.user user table in Mysql

MySQL is a multi-user managed database that can a...

JavaScript to show and hide the drop-down menu

This article shares the specific code for JavaScr...

Full steps to create a password generator using Node.js

Table of contents 1. Preparation 2. Writing comma...

CSS Viewport Units for Fast Layout

CSS Viewport units have been around for the past ...

Explanation of the usage of replace and replace into in MySQL

MySQL replace and replace into are both frequentl...

A brief summary of all encapsulation methods in Vue

Table of contents 1. Encapsulation API 2. Registe...

How to upgrade MySQL 5.6 to 5.7 under Windows

Written in front There are two ways to upgrade My...

Two ideas for implementing database horizontal segmentation

introduction With the widespread popularity of In...

VS2019 connects to mysql8.0 database tutorial with pictures and text

1. First, prepare VS2019 and MySQL database. Both...

Limit input type (multiple methods)

1. Only Chinese characters can be input and pasted...

Text pop-up effects implemented with CSS3

Achieve resultsImplementation Code html <div&g...

Implementation of MySQL scheduled backup script under Windows

On a Windows server, if you want to back up datab...

Detailed explanation of Vue project packaging

Table of contents 1. Related configuration Case 1...