Audio
At this point we have the player spaceship flying through space controlled by the accelerometer input. Let’s add some music to make things more entertaining. Cocos2d-x comes with the CocosDenshion audio library which is multiplatform and isolates the complexity of writing platform specific audio code. It’s very simple to use and allows you to quickly add sound effects to your game.
8. HelloWorldScene.h add the include statement:
#include "SimpleAudioEngine.h"
9. In HelloWorldScene.cpp
(a) Under HelloWorld::init(),add the below right before the schedule updateGame call: .
//Preload sound effects
CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadEffect("shoot.wav");
CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadEffect("explode.wav");
CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadEffect("explode_ship.wav");
CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic("main_background_music.ogg");
CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic("enemy_background_music.ogg");
CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic("enemy_background_music.ogg");
//Play background music with looping enabled
CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("main_background_music.ogg",true);
In the code above, we first preload all the music and sounds effects we will be using throughout the game. This is because loading these on the fly can be expensive and introduce audio lag. Once we have preloaded everything, we can simply call two methods playBackgroundMusic(…) or playSoundEffect(…) to initiate playback.
Build/deploy the project and you will now hear background music playing as the player spaceship flies through space.
You can download the completed source code for this step from here.
Thank you very much.
Written very well.