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:
1 2 3 | #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.
1 2 3 4 5 6 7 | 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:
1 2 3 4 5 6 7 8 9 10 11 | // 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.
http://github.com/ndubbs/CocosDenshion-Example
As always, comments are welcomed and greatly appreciated.




#1 by CharliesD on June 7, 2011 - 1:20 pm
Quote
Thanks for the article. Where on earth do I download CocosDenshion from? Google shows a million people talking about it, and nothing turns up for download locations…
Cheers.
#2 by CharliesD on June 7, 2011 - 1:27 pm
Quote
Ah, found it, problem was I’d found an old page for Cosos2D that had a Denshion-free download on it!
#3 by Roger on October 2, 2011 - 5:26 am
Quote
…and…where do you find it? I’ve been searching all over for the download link as well. It would have been helpful had you posted the link.
#4 by nick on October 2, 2011 - 2:55 pm
Quote
@Roger I’m not sure what you couldn’t find a link for. CocosDenshion comes with Cocos2D. The sample project also has a link on the bottom of the post.
The Cocos2D website is http://www.cocos2d-iphone.org/