以前的内容主要都是介绍如何在屏幕上显示图像,事实上除了图像以外,音乐的播放也能够被理解为一种显示的方式,本节将学习在Cocos2d-x中播放声音的方法。segmentfault
(1)在HelloWorld.h中对HelloWorld类进行以下定义:学习
class HelloWorld : public Cocos2d::Layer { public: bool is_paused; static Cocos2d::Scene* createScene(); virtual bool init(); void play(Cocos2d::Object* pSender); //播放音乐 void stop(Cocos2d::Object* pSender); //中止音乐 void pause(Cocos2d::Object* pSender); //暂停 CREATE_FUNC(HelloWorld); };
(2)在HelloWorldScene.cpp中实现这些方法,如范例3-7所示,完整代码可见源文件本章目录下的项目ChapterThree05。this
【范例3-7 在Cocos2d-x中实现音乐的播放和暂停等操做】spa
#include "HelloWorldScene.h" #include "SimpleAudioEngine.h" USING_NS_CC; Scene* HelloWorld::createScene() { auto scene = Scene::create(); auto layer = HelloWorld::create(); scene->addChild(layer); return scene; } bool HelloWorld::init() { if ( !Layer::init() ) { return false; } is_paused = false; //播放按钮 auto* label_play = Label::create("play", "Arial", 40); auto* pLabel_play = MenuItemLabel::create(label_play, this, menu_selector(HelloWorld::play)); auto* button_play = Menu::create(pLabel_play, NULL); button_play->setPosition(160,180); addChild(button_play); //暂停按钮 auto* label_pause = Label::create("pause", "Arial", 40); auto* pLabel_pause = MenuItemLabel::create(label_pause, this, menu_selector(HelloWorld::pause auto* button_pause = Menu::create(pLabel_pause, NULL); button_pause->setPosition(320,180); addChild(button_pause);30 //中止按钮 auto* label_stop = Label::create("stop", "Arial", 40); auto* pLabel_stop = MenuItemLabel::create(label_stop, this, menu_selector(HelloWorld::stop)); auto* button_stop = Menu::create(pLabel_stop, NULL); button_stop->setPosition(480,180); addChild(button_stop); return true; } void HelloWorld::play(Cocos2d::Object* pSender) { //若是背景音乐被暂停则继续播放 if (is_paused) { CocosDenshion::SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic(); } else { //不然从新播放 CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("music.mp3"); } is_paused = false; } void HelloWorld::stop(Cocos2d::Object* pSender) { //中止音乐 is_paused = false; CocosDenshion::SimpleAudioEngine::sharedEngine()->stopBackgroundMusic(); } void HelloWorld::pause(Cocos2d::Object* pSender) { //暂停播放音乐 is_paused = true; CocosDenshion::SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic(); }
本例运行后的界面如图3-12所示,点击屏幕上的3个标签按钮则会执行音乐的播放、暂停等操做。
图3-12 能够点击按钮进行音乐的播放暂停等操做code
在使用Cocos2d-x播放音乐时须要引入文件SimpleAudioEngine.h(如范例第02行所示),以后就可使用如范例第4二、4六、5三、58行所示的代码来对音乐进行操做了。由于代码很是简单,这里便再也不作太多介绍了。游戏
如今须要读者思考一个问题,为何在播放音乐时使用的方法是playBackgroundMusic而不是playMusic?Background是背景的意思,是否是说这个方法只能用来播放背景音乐?那么什么音乐不是背景音乐呢?游戏开发
实际上该方法是能够播听任何音乐的,可是比较适合播放大段的音乐,而在游戏中大段的音乐经常被用来做为背景音乐使用。在游戏中一些短小的音乐(如怪物的叫声、打斗声等)则是要经过其余方法来播放的,这些内容将在下一节介绍。开发
Cocos2d-x游戏开发学习笔记1--在Cocos2d中显示图像
《Cocos2d-x游戏开发实战精解》学习笔记2--在Cocos2d-x中显示一行文字get