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 background music


By using SimpleAudioEngine, we can play background music very easily. SimpleAudioEngine is a shared singleton object that can be called from anywhere in your code. In SimpleAudioEngine, we can play only one background score.

Getting ready

We have to include the header file of SimpleAudioEngine to use it. Therefore, you will need to add the following code:

#include "SimpleAudioEngine.h"

How to do it...

The following code is used to play background music called background.mp3.

auto audio = CocosDenshion::SimpleAudioEngine::getInstance();
audio->preloadBackgroundMusic("background.mp3");

// play the background music and continuously play it.
audio->playBackgroundMusic("background.mp3", true);

How it works...

SimpleAudioEngine has a namespace called CocosDenshion. For SimpleAudioEngine, you just have to get an instance by using the getInstance method. You can play the background music without preloading it, but this could result in a delay in playback. That's why you...