Outdated Docs > Step by Step Cocos2dxSimpleGame Series > Chapter 6 - How to Play Music and Sound Effect

Chapter 6 - How to Play Music and Sound Effect

In this chapter, we would add background music to the game and play sound effect when the hero fires bullets.

Because there’s so few codes to add that we could say a little more about audio engine here. Cocos2d-x has wrapped SimpleAudioEngine to cross platforms. In our game, we are able to play music and sound effect using only one line of codes. It is so convenient. Of course, audio formats supported in different platform are different, about this issue, you could refer to http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Audio\_formats\_supported\_by\_CocosDenshion\_on\_different\_platforms.

In fact, cocos2d-iphone includes the cocosDenshion library, and the library offers three layers of interfaces: CDSoundEngine->CDAudioManager->SimpleAudioEngine, but its realization totally relies on OpenAL. About OpenAL, it is not a standard of Khronos Group, it is an open source of Creative, which could be realize by software and hardware. So far, OpenAL is hardware realized only by Apple’s products, so in other platforms, we couldn’t provide supports for the lower layers of cocosDenshion, but we support the top layer which is used most commonly by the developers.

Now let’s get right to the issues.
First, copy the sound files background-music-aac.wav and pew-pew-lei.wav to the Resource directory. We use wav here because wav is supported in all platforms and these two files have been included in the Cocos2dSimpleGame project, you could download them from the bottom of this page.
Then include SimpleaudioEngine.h in HelloWorldScene.cpp.

// cpp with cocos2d-x
#include "SimpleAudioEngine.h"  

Add the background music in init().

// cpp with cocos2d-x
"background-music-aac.wav", true);  

And play the sound effect in ccTouchesEnded() when the bullet is fired.

// cpp with cocos2d-x

Ok, the audio addition is completed now.

background-music-aac.wav (1.6 MB) huangrh, 2011-04-14 01:27

pew-pew-lei.wav (48.3 kB) huangrh, 2011-04-14 01:27

Sign up for our newsletter to keep up with the latest developments, releases and updates for Cocos2d-x.