CocosDenshion Sound Engine

Version 0.99 of Cocos2d for the iPhone was just released this week. I am using the Cocos2d framework in my game, and wanted to post a short tutorial/sample code for the CocosDenshion sound engine that is shipping with the latest version.

I am going to start off with the the basic Hello World example that is created for you when you create a new Cocos2d project.


In the HelloWorld.h file add the following lines of code to import the needed files:

#import "SimpleAudioEngine.h"
#import "CocosDenshion.h"
#import "CDAudioManager.h"


Now we will move to the HelloWorld.m file to add the rest of the code. Inside the init method will will preload the background music so there is no lag when opening this layer. Since we only have one layer, it makes no difference. This will help when you have multiple layers in a game. One thing to note, the backgroundMusicVolume can be set from the range of 0.0 to 1.0. If you load a new background music file, you will need to set this again.

SimpleAudioEngine *sae = [SimpleAudioEngine sharedEngine];
if (sae != nil) {
	[sae preloadBackgroundMusic:@"mario-theme.mp3"];
	if (sae.willPlayBackgroundMusic) {		
		sae.backgroundMusicVolume = 0.5f;


To play the background sound and other sounds use the following code:

// Start the background music from the beginning and stop the background music
[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"mario-theme.mp3"];
[[SimpleAudioEngine sharedEngine] stopBackgroundMusic];

// Mute and unmute all sounds
[CDAudioManager sharedManager].mute = TRUE;
[CDAudioManager sharedManager].mute = FALSE;

// Pause and unpause the background music
[[SimpleAudioEngine sharedEngine] pauseBackgroundMusic];
[[SimpleAudioEngine sharedEngine] resumeBackgroundMusic];


As you can see, CocosDenshion is very simple and easy to use. More information on it can be found here.
If you would like to see this in working action, then head on over to my github repository and download the sample project.
As always, comments are welcomed and greatly appreciated.

Share: Share on FacebookShare on Google+Tweet about this on TwitterPin on PinterestEmail this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *