Cocos2d-x实例:设置背景音乐与音效- AppDelegate实现
为了进一步了解背景音乐和音效播放的我们通过一个实例给大家介绍一下。如下图所示有两个场景HelloWorld和Setting。在HelloWorld场景点击“游戏设置”菜单可以切换到Setting场景在Setting场景中可以设置是否播放背景音乐和音效设置完成后点击“OK”菜单可以返回到HelloWorld场景。


我们需要在AppDelegate中实现背景音乐播放暂停与继续函数AppDelegate.h文件代码如下
#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_
上述代码第①行是引入头文件SimpleAudioEngine.h它是SimpleAudioEngine所需要的。第②行代码using namespace CocosDenshion是使用命名空间CocosDenshion它是CocosDenshion引擎所需要的。
#include "AppDelegate.h"
#include "HelloWorldScene.h"
USING_NS_CC;
AppDelegate::AppDelegate() {
}
AppDelegate::~AppDelegate()
{
}
bool AppDelegate::applicationDidFinishLaunching() { ①
… …
// run
director->runWithScene(scene);
//初始化 背景音乐
SimpleAudioEngine::getInstance()->preloadBackgroundMusic("sound/Jazz.mp3"); ②
SimpleAudioEngine::getInstance()->preloadBackgroundMusic("sound/Synth.mp3"); ③
//初始化 音效
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(); ⑧
}
我们在上述代码第①行是声明applicationDidFinishLaunching()函数这个函数是在游戏启动时候调用。第②~④行代码是初始化背景音乐和音效文件。
第⑤行代码是声明applicationDidEnterBackground()是游戏进入到后天时候调用函数在这个函数中需要停止动画和暂停背景音乐播放。第⑦行代码是声明applicationWillEnterForeground()是游戏从后天回到前台时候调用在这个函数中需要继续动画和背景音乐播放。
更多内容请关注最新Cocos图书《Cocos2d-x实战 C++卷》
本书交流讨论网站https://www.cocoagame.net更多精彩视频课程请关注智捷课堂Cocos课程https://v.51work6.com
欢迎加入Cocos2d-x技术讨论群257760386
《Cocos2d-x实战 C++卷》现已上线各大商店均已开售
京东https://item.jd.com/11584534.html
当当https://product.dangdang.com/23606265.html
互动出版网https://product.china-pub.com/3770734
《Cocos2d-x实战 C++卷》源码及样章下载地址
源码下载地址https://51work6.com/forum.php?mod=viewthread&tid=1155&extra=page%3D1
样章下载地址https://51work6.com/forum.php?mod=viewthread&tid=1157&extra=page%3D1
欢迎关注智捷iOS课堂微信公共平台
最后更新:2017-04-03 05:39:44