Cocos2d-x instance: Set background music and sound effects-AppDelegate implementation
To learn more about playing background music and sound effects, let's use an example. As shown in, there are two scenarios: HelloWorld and Setting. In the HelloWorld scenario, click the "game Settings" menu to switch to the Setting scenario. In the Setting scenario, you can set whether to play background music and sound effects, click "OK" to return to the HelloWorld scenario.
We need to implement the function of pausing and resuming playing background music in AppDelegate. The Code of AppDelegate. H 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 first line of the above Code introduces the header file SimpleAudioEngine. h, which is required by SimpleAudioEngine. The second line of code using namespace CocosDenshion uses the namespace CocosDenshion, which is required by the CocosDenshion engine.
# Include AppDelegate. h # include HelloWorldScene. hUSING_NS_CC; AppDelegate: AppDelegate () {} AppDelegate ::~ AppDelegate () {} bool AppDelegate: applicationDidFinishLaunching () {①... ... // Run director-> runWithScene (scene); // initialize the background music SimpleAudioEngine: getInstance ()-> preloadBackgroundMusic (sound/jazzaudio); ② SimpleAudioEngine: getInstance () -> preloadBackgroundMusic (sound/synthloud); ③ // initialize the sound SimpleAudioEngine: getInstance ()-> preloadEffect (sound/Blip.wav); ④ return true;} void AppDelegate :: applicationDidEnterBackground () {⑤ ctor: getInstance ()-> stopAnimation (); SimpleAudioEngine: getInstance ()-> pauseBackgroundMusic (); ⑥} void AppDelegate: applicationWillEnterForeground () {7director: getInstance ()-> startAnimation (); SimpleAudioEngine: getInstance ()-> resumeBackgroundMusic (); Response}
In the above Code, row ① declares the applicationDidFinishLaunching () function, which is called at game startup. ② ~ Line 4 of code initializes the background music and audio files.
The fifth line of Code declares that applicationDidEnterBackground () Is the function called when the game enters the day after tomorrow. In this function, you need to stop the animation and pause the background music. The Code in line 7 declares that applicationWillEnterForeground () is called when the game returns to the foreground from the day after tomorrow. In this function, you need to continue playing the animation and background music.