to learn more about background music and sound effects, let's introduce you through an example. There are two scenarios as shown: HelloWorld and setting. In the HelloWorld scene, click on the "Game Settings" menu can switch to the setting scene, in the setting scene can set whether to play the background music and sound effects, after the settings are complete, click on the "OK" menu can be returned to the HelloWorld scene.
We need to implement the background music playback pause and continue function in Appdelegate, the AppDelegate.h file code is as follows:
#ifndef _app_delegate_h_#define _app_delegate_h_#include "cocos2d.h" #include "SimpleAudioEngine.h" ①using namespace Cocosdenshion;②class appdelegate:private cocos2d::application{public: appdelegate (); Virtual ~appdelegate (); virtual bool applicationdidfinishlaunching (); virtual void Applicationdidenterbackground (); virtual void Applicationwillenterforeground ();}; #endif//_app_delegate_h_
The above code line ① is the introduction of the header file SimpleAudioEngine.h, which is required by Simpleaudioengine. The ② line code using namespace Cocosdenshion is used with the namespace cocosdenshion, which is required by the Cocosdenshion engine.
#include "AppDelegate.h" #include "HelloWorldScene.h" USING_NS_CC; Appdelegate::appdelegate () {}appdelegate::~appdelegate () {}bool appdelegate::applicationdidfinishlaunching () {① ... //Run director->runwithscene (scene);//Initialize background music simpleaudioengine::getinstance () Preloadbackgroundmusic ("Sound/jazz.mp3"); ②simpleaudioengine::getinstance ()->preloadbackgroundmusic ("sound/ Synth.mp3 ") ③//Initialize Sound simpleaudioengine::getinstance ()->preloadeffect (" Sound/blip.wav "); ④ return true;} void Appdelegate::applicationdidenterbackground () {⑤ director::getinstance ()->stopanimation (); Simpleaudioengine::getinstance ()->pausebackgroundmusic (); ⑥}void Appdelegate::applicationwillenterforeground ( ) {⑦ director::getinstance ()->startanimation (); Simpleaudioengine::getinstance ()->resumebackgroundmusic (); ⑧}
Our ① line in the above code is the declaration of the Applicationdidfinishlaunching () function, which is called when the game starts. The ②~④ line code is the initial background music and sound effects file.
The ⑤ Line code is declared Applicationdidenterbackground () is the game enters the day after the call function, in this function need to stop the animation and pause the background music playback. The ⑦ Line code is declared Applicationwillenterforeground () is called when the game returns to the foreground from the day after tomorrow, in which the animation and background music playback needs to continue.
For more information, please pay attention to Cocos2d-x series book "Cocos2d-x Combat (Volume Ⅰ): C + + development" book Exchange Discussion website: http://www.cOcoagame.netWelcome to join Cocos2d-x Technical discussion group:257760386.327403678