您的位置:首页 > 移动开发 > Cocos引擎

Cocos2d-x实例:设置背景音乐与音效- AppDelegate实现

2014-08-05 19:23 573 查看

为了进一步了解背景音乐和音效播放的,我们通过一个实例给大家介绍一下。如下图所示有两个场景: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++卷》‍本书交流讨论网站:http://www.cocoagame.net
更多精彩视频课程请关注智捷课堂Cocos课程:http://v.51work6.com
欢迎加入Cocos2d-x技术讨论群:257760386‍
《Cocos2d-x实战 C++卷》现已上线,各大商店均已开售:‍
京东:http://item.jd.com/11584534.html
亚马逊:http://www.amazon.cn/Cocos2d-x%E5%AE%9E%E6%88%98-C-%E5%8D%B7-%E5%85%B3%E4%B8%9C%E5%8D%87/dp/B00PTYWTLU
当当:http://product.dangdang.com/23606265.html
互动出版网:http://product.china-pub.com/3770734

《Cocos2d-x实战 C++卷》源码及样章下载地址:
源码下载地址:http://51work6.com/forum.php?mod=viewthread&tid=1155&extra=page%3D1
样章下载地址:http://51work6.com/forum.php?mod=viewthread&tid=1157&extra=page%3D1
欢迎关注智捷iOS课堂微信公共平台
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: