cocos2dx 玩转音乐播放

前端之家收集整理的这篇文章主要介绍了cocos2dx 玩转音乐播放前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

PlayMusic.cpp

#include "PlayMusic.h"
#include "SimpleAudioEngine.h"
#include "iconv/iconvString.h"//报错请查下面看注意事项
#include "SystemHeader.h"//报错请查下面看注意事项
USING_NS_CC;
using namespace CocosDenshion;
//根据不同的平台使用的预编译索引不同音频文件
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#define EFFECT_FILE "effect2.ogg"
#elif (CC_TARCET_PLATFORM == CC_PLATFORM_MARMALADE)
#define EFFECT_FILE "effect1.raw"
#else
#define EFFECT_FILE "sound/FX088.mp3"
#endif

#if (CC_TARGET_PLATEFOM == CC_PLATFORM_WIN32)
#define MUSIC_FILE "music.mid"
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY)
#define MUSIC_FILE "background.ogg"
#else
#define MUSIC_FILE "sound/BACK_MUSIC.mp3"
#endif


std::string items[] = {
    "播放背景音乐","停止背景音乐","暂停背景音乐","继续播放背景音乐","后退背景音乐","背景音乐是否播放","播放音效","重复播放音效","停止音效播放","释放音效","增加背景音乐音量","减少背景音效音量","增加音效音量","减少音效音量","暂停音效","继续播放音效","暂停所有音效","继续所有音效","停止所有音效"
};
unsigned int PlayMusic::effectId = 0;
Scene* PlayMusic::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();

    // 'layer' is an autorelease object
    PlayMusic *layer = PlayMusic::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool PlayMusic::init()
{
    //////////////////////////////
    // 1. super init first
    if (!Layer::init())
    {
        return false;
    }
    code_convert_init();
    //
    CCMenu * m_pItmeMenu = CCMenu::create();
    CCSize size = CCDirector::sharedDirector()->getWinSize();
    int m_nTestCount = sizeof(items) / sizeof(items[0]);

    for (int i = 0; i<=18;i++)
    {
        LabelTTF * label = LabelTTF::create(gbktoutf8(items[i].c_str()),"",20);
        label->setColor(Color3B::GREEN);
        MenuItemLabel * pMenuItem = MenuItemLabel::create(label,CC_CALLBACK_1(PlayMusic::menuBack,this));
        m_pItmeMenu->addChild(pMenuItem,i);
        pMenuItem->setPosition(CCPointMake(0,(size.height*0.5  - (i + 1) * 30)));
    }
    addChild(m_pItmeMenu,0,100);

    // 预加载音乐和音效
    SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic(MUSIC_FILE);
    SimpleAudioEngine::sharedEngine()->preloadEffect(EFFECT_FILE);

    // 设置默认音量
    SimpleAudioEngine::sharedEngine()->setEffectsVolume(0.5);
    SimpleAudioEngine::sharedEngine()->setBackgroundMusicVolume(0.5);

    // CCUserDefault::sharedUserDefault()->setStringForKey("name","baibai");
    SaveStringToXML("name","baibai");
    CCUserDefault::sharedUserDefault()->flush();//写了东西要提交 

    // std::string name = CCUserDefault::sharedUserDefault()->getStringForKey("name");
    std::string name = LoadStringFromXML("name");
    log("name: %s ",name.c_str());
    log("%s",FileUtils::getInstance()->getWritablePath().c_str());


    Size winSize = CCDirector::getInstance()->getWinSize();
    Point pCenter = Point(winSize.width / 2,winSize.height / 2);
    ControlPotentiometer* potentiometer = ControlPotentiometer::create("potentiometerTrack.png","potentiometerProgress.png","potentiometerButton.png");
    potentiometer->setPosition(Point(winSize.width / 2 - 200,winSize.height / 2));
    //监听进度值改变事件 
    potentiometer->addTargetWithActionForControlEvents(this,cccontrol_selector(PlayMusic::onValueChange),Control::EventType::VALUE_CHANGED);
    this->addChild(potentiometer);

    ControlSlider* slider = ControlSlider::create("sliderTrack.png","sliderProgress.png","sliderThumb.png");
    slider->setPosition(Point(winSize.width / 2-200,winSize.height / 2 - 80));
    //设置滑动条的范围 
    slider->setMinimumValue(0.0f);
    slider->setMaximumValue(1.0f);
    //设置滑动条当前值 
    slider->setValue(0.5f);
    slider->addTargetWithActionForControlEvents(this,cccontrol_selector(PlayMusic::sliderChange),Control::EventType::VALUE_CHANGED);
    this->addChild(slider);


    //得到窗口的大小
    ///CCSize winSize = CCDirector::sharedDirector()->getWinSize();
    //设置ControlSwitch控件打开的文字No"
    Label* On = Label::create("ON","fonts/arial.ttf",16);
    //设置ControlSwitch控件关闭时的文字"OFF"
    Label* Off = Label::create("OFF",16);
    //设置ControlSwitch控件打开的文字的颜色
    On->setColor(ccc3(0,0));
    //设置ControlSwitch控件关闭时的颜色
    Off->setColor(ccc3(0,0));
    //创建ControlSwitch控件
    ControlSwitch *switchControl = ControlSwitch::create(
        Sprite::create("switch-mask.png"),Sprite::create("switch-on.png"),Sprite::create("switch-off.png"),Sprite::create("switch-thumb.png"),On,Off
        );
    //设置ControlSwitch控件的位置
    switchControl->setPosition(Point(winSize.width / 2-200,winSize.height / 2 + 80));
    // 注册valuechange消息,当valuechange时,调用switchValueChanged函数
    switchControl->addTargetWithActionForControlEvents(this,cccontrol_selector(PlayMusic::switchValueChanged),Control::EventType::VALUE_CHANGED);
    //添加ControlSwitch控件
    addChild(switchControl);
return true;
}
void PlayMusic::switchValueChanged(Ref* psender,Control::EventType event)
{
    if (event == Control::EventType::VALUE_CHANGED)
    {
        ControlSwitch* control = (ControlSwitch*)psender;
        if (control->isOn())
        {
            SaveBooleanToXML("SOUND_KEY",true);
            SaveBooleanToXML("MUSIC_KEY",true);
            // CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("BACK_MUSIC.wav",true);
            // CocosDenshion::SimpleAudioEngine::sharedEngine()->resumeAllEffects();
            //log("Switch if ON");
        }
        else
        {
            SaveBooleanToXML("SOUND_KEY",false);
            SaveBooleanToXML("MUSIC_KEY",false);
            // CocosDenshion::SimpleAudioEngine::sharedEngine()->stopBackgroundMusic("BACK_MUSIC.wav");
            // CocosDenshion::SimpleAudioEngine::sharedEngine()->pauseAllEffects();
            //log("Swith is Off");
        }
    }
    else
    {
        log("other events");
    }
}



void PlayMusic::sliderChange(Ref* psender,Control::EventType event)
{
    ControlSlider* slider = (ControlSlider*)psender;
    String* valueStr = String::createWithFormat("%f",slider->getValue());
    CocosDenshion::SimpleAudioEngine::sharedEngine()->setBackgroundMusicVolume((float)slider->getValue());
    //log("setBackgroundMusicVolume=%f",CocosDenshion::SimpleAudioEngine::sharedEngine()->getBackgroundMusicVolume());
    //log(valueStr->getCString());
}


void PlayMusic::onValueChange(Ref* psender,Control::EventType event)
{
    ControlPotentiometer* potentiometer = (ControlPotentiometer*)psender;
    String* valueStr = String::createWithFormat("%f",potentiometer->getValue());
    CocosDenshion::SimpleAudioEngine::sharedEngine()->setBackgroundMusicVolume((float)potentiometer->getValue());
    //log("onValueChange=%f",(float)potentiometer->getValue());
    // log("setBackgroundMusicVolume=%f",CocosDenshion::SimpleAudioEngine::sharedEngine()->getBackgroundMusicVolume());
    // log(valueStr->getCString());
}
void PlayMusic::menuBack(Ref * pSender)
{

    CCMenuItem * pMenuItem = (CCMenuItem *)(pSender);
    int nIdx = pMenuItem->getZOrder();
    switch (nIdx) {
    case 0:
        // 播放背景音乐
        SimpleAudioEngine::sharedEngine()->playBackgroundMusic(MUSIC_FILE,true);
        break;
    case 1:
        // 停止背景音乐
        SimpleAudioEngine::sharedEngine()->stopBackgroundMusic();
        break;
    case 2:
        // 暂停背景音乐
        SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
        break;
    case 3:
        // 继续播放背景音乐
        SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
        break;
    case 4:
        // 后退背景音乐
        SimpleAudioEngine::sharedEngine()->rewindBackgroundMusic();
        break;
    case 5:
        // 背景音乐是否正在播放
        if (SimpleAudioEngine::sharedEngine()->isBackgroundMusicPlaying()) {
            CCLOG("playing");
        }
        else
            CCLOG("no play");
        break;
    case 6:
        // 播放音效,并且得到此音效的ID
        SimpleAudioEngine::sharedEngine()->playEffect(EFFECT_FILE);
        break;
    case 7:
        // 重复播放音效
        effectId =SimpleAudioEngine::sharedEngine()->playEffect(EFFECT_FILE,true);
        break;
    case 8:
        // 停止播放音效
        SimpleAudioEngine::sharedEngine()->stopEffect(effectId);
        break;
    case 9:
        // 释放音效
        SimpleAudioEngine::sharedEngine()->unloadEffect("effect1.wav");
        break;
    case 10:
        // 增加背景音乐音量
        SimpleAudioEngine::sharedEngine()->setBackgroundMusicVolume(SimpleAudioEngine::sharedEngine()->getBackgroundMusicVolume() + 0.1f);
        break;
    case 11:
        // 减少背景音乐音量
        SimpleAudioEngine::sharedEngine()->setBackgroundMusicVolume(SimpleAudioEngine::sharedEngine()->getBackgroundMusicVolume() - 0.1f);
        break;
    case 12:
        // 增加背景音效音量
        SimpleAudioEngine::sharedEngine()->setEffectsVolume(SimpleAudioEngine::sharedEngine()->getEffectsVolume() + 0.1f);
        break;
    case 13:
        // 减少背景音效音量
        SimpleAudioEngine::sharedEngine()->setEffectsVolume(SimpleAudioEngine::sharedEngine()->getEffectsVolume() - 0.1f);
        break;
    case 14:
        // 暂停音效
        SimpleAudioEngine::sharedEngine()->pauseEffect(effectId);
        break;
    case 15:
        // 继续 播放音效
        SimpleAudioEngine::sharedEngine()->resumeEffect(effectId);
        break;
    case 16:
        // 暂停所有音效
        SimpleAudioEngine::sharedEngine()->pauseAllEffects();
        break;
    case 17:
        // 继续所有音效
        SimpleAudioEngine::sharedEngine()->resumeAllEffects();
        break;
    case 18:
        // 停止所有音效
        SimpleAudioEngine::sharedEngine()->stopAllEffects();
        break;

    default:
        break;
    }

}

PlayMusic.h

#ifndef _PLAY_MUSIC_H_
#define _PLAY_MUSIC_H_
#include "cocos2d.h"
#include "cocos-ext.h"

using namespace cocos2d;
using namespace cocos2d::extension;
class PlayMusic : public cocos2d::Layer
{
public:
    // 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();

    // a selector callback

    // implement the "static create()" method manually
    CREATE_FUNC(PlayMusic);
    void menuBack(Ref * pSender);
    void onValueChange(Ref* psender,Control::EventType event);
    void sliderChange(Ref* psender,Control::EventType event);
    void switchValueChanged(Ref* psender,Control::EventType event);
    static unsigned int effectId;
protected:


};

#endif

注意事项:
1、如果#include “iconv/iconvString.h”这里报错,请参照我另一篇文章 cocos2d-x 3.4 中文乱码解决之道 2、如果#include “SystemHeader.h”这里报错,请参照我下一篇文章,也可以去掉报错的地方,这里是保存音乐设置

原文链接:https://www.f2er.com/cocos2dx/341602.html

猜你在找的Cocos2d-x相关文章