Book Image

Cocos2d-x Cookbook

By : Akihiro Matsuura
Book Image

Cocos2d-x Cookbook

By: Akihiro Matsuura

Overview of this book

Table of Contents (18 chapters)
Cocos2d-x Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Playing a sound effect


By using SimpleAudioEngine, we can play sound effects; to play them, we need to perform only two steps, namely preload and play. Sound effects are not background music; note that we can play multiple sound effects but only one background score at the same time. In this recipe, we will explain how to play sound effects.

Getting ready

As in the case of playing background music, you have to include a header file for SimpleAudioEngine.

#include "SimpleAudioEngine.h"

How to do it...

Let's try to immediately play a sound effect. The audio format is changed depending on the operating system by using the macro that was introduced at the time of playing the background music. The code for playing sound effects is as follows:

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) 
#define EFFECT_FILE        "effect.ogg" 
#else 
#define EFFECT_FILE        "effect.caf" 
#endif

auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
audio->preloadEffect( EFFECT_FILE ); 
audio->playEffect...