cocos02:播放声音

2016-09-08  本文已影响63人  武林盟主和穿山甲

游戏中来说声音有两种情况,一种是游戏的背景音,这种音乐时间较长。另一种就是类似怪物发出的声音,这种声音时间较短。这两种播放音乐的方式代码是不同的。

第一种:

先在.h文件中定义

class HelloWorld : public cocos2d::Layer

{

public:

bool is_paused;

// there's no 'id' in cpp, so we recommend returning the class instance pointer

static cocos2d::Scene* createScene();

// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone

virtual bool init();

void play(cocos2d::Object*pSender);//播放

void stop(cocos2d::Object*pSender);//停止

void pause(cocos2d::Object*pSender);//暂停

// implement the "static create()" method manually

CREATE_FUNC(HelloWorld);

};

然后进入.cpp文件

先导入#include "SimpleAudioEngine.h"

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 *pLaebl_pause = MenuItemLabel::create(label_pause, this, menu_selector(HelloWorld::pause));

auto *button_pause = Menu::create(pLaebl_pause, NULL);

button_pause->setPosition(320,180);

addChild(button_pause);

//停止

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);

之后编写方法

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::pause(cocos2d::Object* pSender)

{

is_paused = false;

CocosDenshion::SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();

}

void HelloWorld::stop(cocos2d::Object* pSender)

{

is_paused = false;

CocosDenshion::SimpleAudioEngine::sharedEngine()->stopBackgroundMusic();

}

然后比较短的声音只需要把palyBackgroundMusic改成playEffect就可以了。我看书上还有一个钢琴的例子。。。先去吃饭。。耶

上一篇下一篇

猜你喜欢

热点阅读