本人用的是VS2013
在HelloWorldScene.h文件中添加三个成员函数,play(播放) stop(停止) pause(暂停)
在HelloWorldScene.cpp文件中
#include "HelloWorldScene.h"
#include "cocostudio/CocoStudio.h"
#include "ui/CocosGUI.h"
#include"SimpleAudioEngine.h" //添加播放音乐的头文件
USING_NS_CC;
using namespace cocostudio::timeline;
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(200, 350);
addChild(button_play);
//停止按钮
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(400, 350);
addChild(button_stop);
//暂停按钮
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(600, 350);
addChild(button_pause);
return true;
}
void HelloWorld::menu(Ref* pSender)
{
}
void HelloWorld::play(Ref* pSender)
{
//如果背景音乐暂停,则继续播放
if (is_paused)
{
//继续播放
CocosDenshion::SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
}
else
{
//否则重新播放,这里的音乐自己准备,音乐放在项目的Resources目录下,皆可
CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("Dj Titon .mp3");
}
}
void HelloWorld::stop(Ref* pSender)
{
is_paused = false;
CocosDenshion::SimpleAudioEngine::sharedEngine()->stopBackgroundMusic();
}
void HelloWorld::pause(Ref* pSender)
{
is_paused = true;
CocosDenshion::SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
}
点击运行,可以看到下面的图片,左下角的参数可以忽略,可以点击三个按钮,看看有什么变化