Cocos2d-x3.2 音乐和音效的播放

//GameScene.h
#include "cocos2d.h"

USING_NS_CC;

class GameScene : public cocos2d::Layer
{
public:
    static cocos2d::Scene* createScene();
    
    virtual bool init();
    
    void menuCallback1(Ref* pSender);
    void menuCallback2(Ref* pSender);
    
    CREATE_FUNC(GameScene);
    
private:        //注意不能用auto关键字
    Size size;
    Sprite *sprite;
};



//GameScene.cpp

#include "GameScene.h"
//声音头文件及命名空间
#include "SimpleAudioEngine.h"
using namespace CocosDenshion;

USING_NS_CC;

//采用宏定义文件名,便于以后统一修改
#define BG_MUSIC "background.mp3"
#define EFFECT_MUSIC "effect1.wav"

cocos2d::Scene* GameScene::createScene()
{
    auto scene = Scene::create();   //创建一个场景
    auto layer = GameScene::create();   //创建一个图层
    scene->addChild(layer);
    return scene;
}

//初始化当前的图层
bool GameScene::init()
{
    if(!Layer::init())      //初始化父类
        return false;
    
    //获取屏幕大小
    size = Director::getInstance()->getVisibleSize();
    //auto size = Director::getInstance()->getWinSize();
    
    auto item1 = MenuItemFont::create("playBackgroundMusic", CC_CALLBACK_1(GameScene::menuCallback1, this));
    item1->setPosition(Vec2(size.width/2, size.height/2));
    auto item2 = MenuItemFont::create("playEffect", CC_CALLBACK_1(GameScene::menuCallback2, this));
    item2->setPosition(Vec2(size.width/2, size.height*0.4));
    
    auto menu = Menu::create(item1, item2, NULL);
    menu->setPosition(Vec2::ZERO);
    this->addChild(menu);
    
    //加载音乐和音效文件
    SimpleAudioEngine::getInstance()->preloadBackgroundMusic(BG_MUSIC);
    SimpleAudioEngine::getInstance()->preloadEffect(EFFECT_MUSIC);
    
    return true;
}

void GameScene::menuCallback1(Ref* pSender)
{
    //播放音乐
    SimpleAudioEngine::getInstance()->playBackgroundMusic(BG_MUSIC);
}

void GameScene::menuCallback2(Ref* pSender)
{
    //播放音效
    SimpleAudioEngine::getInstance()->playEffect(EFFECT_MUSIC);
}


你可能感兴趣的:(Cocos2d-x3.2 音乐和音效的播放)