#ifndef __NewAudioEngineDemo__NewAudioEngineDemo__#define __NewAudioEngineDemo__NewAudioEngineDemo__#include "cocos2d.h"#include "ui/CocosGUI.h"#include "VisibleRect.h"#include "audio/include/AudioEngine.h"USING_NS_CC;using namespace ui;class NewAudioEngineDemo : public Scene{public: CREATE_FUNC(NewAudioEngineDemo); virtual bool init();};class BaseTest : public Layer{public: CREATE_FUNC(BaseTest); virtual bool init(); virtual std::string Title() const;//主标题 virtual std::string subTitle() const;//副标题 virtual voID onExit() overrIDe; virtual voID restartCallback(Ref* sender);//重新执行当前test virtual voID nextCallback(Ref* sender);//下一个test virtual voID backCallback(Ref* sender);//上一个test voID menuCloseCallback(cocos2d::Ref* pSender);//关闭菜单回调函数};class AudioControlTest : public BaseTest{public: CREATE_FUNC(AudioControlTest); virtual ~AudioControltest(); virtual bool init(); virtual voID update(float dt); virtual std::string subTitle() const overrIDe;private: int _audioID; bool _loopEnabled; float _volume; float _duration; float _timeRatio; voID* _playItem; voID* _timeSlIDer; bool _updateTimeSlIDer;};class PlaySimultaneouslyTest : public BaseTest{public: CREATE_FUNC(PlaySimultaneouslyTest); virtual ~PlaySimultaneouslytest(); virtual bool init(); virtual std::string subTitle() const overrIDe;private: static const int TEST_COUNT = 10; std::string _files[TEST_COUNT]; voID* _playItem; int _playingcount;};class AudioProfileTest : public BaseTest{public: CREATE_FUNC(AudioProfileTest); virtual bool init(); virtual ~AudioProfiletest(); virtual std::string subTitle() const overrIDe; virtual voID update(float dt);private: static const int file_COUNT = 2; std::string _files[file_COUNT]; cocos2d::experimental::AudioProfile _audioProfile; int _audioCount; Label* _showLabel; float _time; float _minDelay; voID* _timeSlIDer;};class InvalIDAudiofileTest : public BaseTest{public: CREATE_FUNC(InvalIDAudiofileTest); virtual bool init(); virtual ~InvalIDAudiofiletest(); virtual std::string subTitle() const overrIDe;};class LargeAudiofileTest : public BaseTest{public: CREATE_FUNC(LargeAudiofileTest); virtual bool init(); virtual ~LargeAudiofiletest(); virtual std::string subTitle() const overrIDe;};#endif /* defined(__NewAudioEngineDemo__NewAudioEngineDemo__) */2、.cpp文件
#include "NewAudioEngineDemo.h"#include "platform/CCPlatformConfig.h"#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32using namespace cocos2d::experimental;#define CL(__classname__) [](){ return __classname__::create();}static int sceneIDx = -1;static std::function<Layer*()> createFunctions[] ={ CL(AudioControlTest),CL(PlaySimultaneouslyTest),CL(AudioProfileTest),CL(InvalIDAudiofileTest),CL(LargeAudiofileTest)};#define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0]))static Layer* nextAction(){ sceneIDx++; sceneIDx = sceneIDx % MAX_LAYER; auto layer = (createFunctions[sceneIDx])(); return layer;}static Layer* backAction(){ sceneIDx--; int total = MAX_LAYER; if( sceneIDx < 0 ) sceneIDx += total; auto layer = (createFunctions[sceneIDx])(); return layer;}static Layer* restartAction(){ auto layer = (createFunctions[sceneIDx])(); return layer;}//基类Layerbool BaseTest::init(){ bool bRet = false; do{ CC_BREAK_IF(!Layer::init()); Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image,which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "Closenormal.png","CloseSelected.png",CC_CALLBACK_1(BaseTest::menuCloseCallback,this)); closeItem->setposition(Vec2(origin.x + visibleSize.wIDth - closeItem->getContentSize().wIDth/2,origin.y + visibleSize.height - closeItem->getContentSize().height/2)); // create menu,it's an autorelease object auto menu1 = Menu::create(closeItem,NulL); menu1->setposition(Vec2::ZERO); this->addChild(menu1,1); std::string str = Title(); const char * pTitle = str.c_str(); TTFConfig ttfConfig("Fonts/tahoma.ttf",35); auto label = Label::createWithTTF(ttfConfig,pTitle); addChild(label,9999); label->setposition( Vec2(VisibleRect::center().x,VisibleRect::top().y - 30) ); std::string strSubTitle = subTitle(); if( ! strSubTitle.empty() ) { ttfConfig.FontfilePath = "Fonts/tahoma.ttf"; ttfConfig.FontSize = 30; auto l = Label::createWithTTF(ttfConfig,strSubTitle.c_str()); addChild(l,9999); l->setposition( Vec2(VisibleRect::center().x,VisibleRect::top().y - 100) ); } auto item1 = MenuItemFont::create("backCallback",CC_CALLBACK_1(BaseTest::backCallback,this) ); auto item2 = MenuItemFont::create("restartCallback",CC_CALLBACK_1(BaseTest::restartCallback,this) ); auto item3 = MenuItemFont::create("nextCallback",CC_CALLBACK_1(BaseTest::nextCallback,this) ); auto menu = Menu::create(item1,item2,item3,NulL); menu->setposition(Vec2::ZERO); item1->setposition(Vec2(VisibleRect::center().x - item2->getContentSize().wIDth*2,VisibleRect::bottom().y+item2->getContentSize().height/2)); item2->setposition(Vec2(VisibleRect::center().x,VisibleRect::bottom().y+item2->getContentSize().height/2)); item3->setposition(Vec2(VisibleRect::center().x + item2->getContentSize().wIDth*2,VisibleRect::bottom().y+item2->getContentSize().height/2)); addChild(menu,9999); bRet = true; }while(0); return bRet;}voID BaseTest::menuCloseCallback(Ref* pSender){#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) MessageBox("You pressed the close button. windows Store Apps do not implement a close button.","Alert"); return;#endif Director::getInstance()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0);#endif}//重新执行当前testvoID BaseTest::restartCallback(cocos2d::Ref *sender){ auto s = new (std::nothrow) NewAudioEngineDemo(); s->addChild(restartAction()); Director::getInstance()->replaceScene(s); s->release();}//下一个testvoID BaseTest::nextCallback(cocos2d::Ref *sender){ auto s = new (std::nothrow) NewAudioEngineDemo(); s->addChild(nextAction()); Director::getInstance()->replaceScene(s); s->release();}//上一个testvoID BaseTest::backCallback(cocos2d::Ref *sender){ auto s = new (std::nothrow) NewAudioEngineDemo(); s->addChild(backAction()); Director::getInstance()->replaceScene(s); s->release();}//onExit函数voID BaseTest::onExit(){ AudioEngine::stopAll(); Layer::onExit();}std::string BaseTest::Title() const{ return "NewAudioEngineDemo Test";}std::string BaseTest::subTitle() const{ return "";}//封装按钮class Textbutton : public cocos2d::Label{public: //静态创建函数 static Textbutton* create(const std::string& text,const std::function<voID(Textbutton*)>& onTriggered) { //如果非配内存失败,返回0 auto ret = new(std::nothrow) Textbutton(); TTFConfig ttfconfig("Fonts/arial.ttf",25); //创建成功,设置Label if(ret && ret->setTTFConfig(ttfconfig)) { //设置内容 ret->setString(text); //设置回调函数 ret->_onTriggered = onTriggered; ret->autorelease(); return ret; } delete ret; return nullptr; } //设置触摸响应 voID setEnabled(bool enabled) { _enabled = enabled; //如果没有触摸 if(_enabled) { //设置Lable颜色为White this->setcolor(color3B::WHITE); }else{ //如果已经触摸,设置颜色Gray this->setcolor(color3B::GRAY); } }private: //构造函数,_enabled为true,_onTriggered为nullptr Textbutton() :_enabled(true),_onTriggered(nullptr) { //注册监听事件 auto Listener = EventListenertouchOneByOne::create(); Listener->setSwallowtouches(true);//事件禁止向下传递 //触摸事件类型 Listener->ontouchBegan = CC_CALLBACK_2(Textbutton::ontouchBegan,this); Listener->ontouchended = CC_CALLBACK_2(Textbutton::ontouchended,this); Listener->ontouchCancelled = CC_CALLBACK_2(Textbutton::ontouchCancelled,this); //加入事件 Director::getInstance()->getEventdispatcher()->addEventListenerWithSceneGraPHPriority(Listener,this); } //判断是否在触摸范围内 bool touchHits(touch* touch) { //将屏幕坐标转为节点坐标 auto hitPos = this->convertToNodeSpace(touch->getLocation()); //触摸点在节点坐标内,返回true,否则返回false if(hitPos.x >= 0 && hitPos.y >= 0 && hitPos.x <= _contentSize.wIDth && hitPos.y <= _contentSize.height) { return true; } return false; } //触摸开始 bool ontouchBegan(touch* touch,Event* event) { //调用touchHit函数,返回true,在节点上 auto hits = touchHits(touch); if(hits) { scalebuttonTo(0.95f);//执行按钮缩放 } return hits;//响应后面触摸事件 } //触摸结束 voID ontouchended(touch* touch,Event* event) { //如果没有触摸 if(_enabled) { //判断是否在节点上 auto hits = touchHits(touch); //如果在节点上,且响应事件不为nullptr if(hits && _onTriggered) { //调用响应事件 _onTriggered(this); } } //执行按钮缩放 scalebuttonTo(1); } //触摸取消 voID ontouchCancelled(touch* touch,Event* event) { scalebuttonTo(1); } //缩放 *** 作 voID scalebuttonTo(float scale) { auto action = Scaleto::create(0.05f,scale); action->setTag(10000); stopActionByTag(10000); runAction(action); } //事件回调函数指针 std::function<voID(Textbutton*)> _onTriggered; bool _enabled;//是否触摸};//封装进度条类,拖动进度条响应事件class SlIDerEx : public SlIDer{public: //触摸事件,按下,移动,抬起,取消 enum class touchEvent { DOWN,MOVE,UP,CANCEL }; //定义函数函数指针 typedef std::function<voID(SlIDerEx*,float,touchEvent)> ccslIDerExCallback; //静态创建函数 static SlIDerEx* create() { //std::nothrow分配内存失败返回0,必须包含头文件#include <new> auto ret = new(std::nothrow)SlIDerEx(); if(ret && ret->init()) { //初始化进度条 ret->_callback = nullptr; ret->loadbarTexture("slIDerTrack.png"); ret->loadSlIDBallTextures("slIDerThumb.png","slIDerThumb.png",""); ret->loadProgressbarTexture("slIDerProgress.png"); ret->autorelease(); return ret; } //如果分配内存失败,删除ret并置空 CC_SAFE_DELETE(ret); return ret; } //设置回调函数 voID setCallBack(const ccslIDerExCallback& callback){ _callback = callback; } //设置进度比 voID setRatio(float ratio) { if(ratio > 1.0f) { ratio = 1.0f; }else if(ratio < 0.0f) { ratio = 0.0f; } _ratio = ratio; _percent = 100* _ratio; //设置进度条光标的位置, float dis = _barLength * _ratio; _slIDBallRenderer->setposition(dis,_contentSize.height/2.0f); //设置进度条已走过的进度 if(_scale9Enabled) { //如果开启9宫格精灵,设置进度条已走过的进度比 _progressbarRenderer->setPreferredSize(Size(dis,_progressbarTextureSize.height)); }else{ //如果没有开启9宫格精灵 //首先获取进度条Progressbar的精灵 auto spriteRenderer = _progressbarRenderer->getSprite(); //精灵不为空 if(nullptr != spriteRenderer) { //获取精灵的Rect Rect rect = spriteRenderer->getTextureRect(); rect.size.wIDth = _progressbarTextureSize.wIDth * _ratio;//设置获取精灵的Rect大小 spriteRenderer->setTextureRect(rect,spriteRenderer->isTextureRectRotated(),rect.size);//设置Progressbar精灵的Rect } } } //触摸开始事件 virtual bool ontouchBegan(touch* touch,Event* unusedEvent) overrIDe{ //进度条开始触摸 auto ret = SlIDer::ontouchBegan(touch,unusedEvent); //_callback不为空 if(ret && _callback){ _touchEvent = touchEvent::DOWN; Vec2 nsp = convertToNodeSpace(_touchBeganposition);//触摸点坐标转为节点坐标 _ratio = nsp.x / _barLength;//取得进度比,当前触摸位置除以进度条的长度 if(_ratio < 0.0f) { _ratio = 0.0f; }else if(_ratio > 1.0f) { _ratio = 1.0f; } _callback(this,_ratio,_touchEvent);//回调事件 } return ret; } //移动触摸 virtual voID ontouchmoved(touch* touch,Event* unusedEvent) overrIDe{ _touchEvent = touchEvent::MOVE;//设置触摸类型 SlIDer::ontouchmoved(touch,unusedEvent);//SlIDer基类触摸 Vec2 nsp = convertToNodeSpace(_touchmoveposition);//触摸点坐标转为节点坐标 _ratio = nsp.x / _barLength; if(_ratio < 0.0f) { _ratio = 0.0f; }else if(_ratio > 1.0f) { _ratio = 1.0f; } if(_callback) { _callback(this,_touchEvent);//事件回调 } } //取消触摸 virtual voID ontouchCancelled(touch* touch,Event* unusedEvent) overrIDe { _touchEvent = touchEvent::CANCEL; SlIDer::ontouchCancelled(touch,unusedEvent); if (_callback) { _callback(this,_touchEvent);//事件回调 } } private: touchEvent _touchEvent;//触摸事件类型 float _ratio;//进度比 ccslIDerExCallback _callback;//回调事件的指针函数};//基类Scenebool NewAudioEngineDemo::init(){ bool bRet; do{ CC_BREAK_IF(!Scene::init()); //初始化AudioEngine CCASSERT(AudioEngine::lazyInit(),"Fail to initialize AudioEngine!"); //初始化sceneIDx sceneIDx = -1; //执行nextAction,执行第一个test auto layer = nextAction(); //加入NewAudioEngineDemo场景 addChild(layer); //切换场景 Director::getInstance()->replaceScene(this); bRet = true; }while(0); return bRet;}bool AudioControlTest::init(){ bool bRet = false; do{ CC_BREAK_IF(!BaseTest::init()); _audioID = AudioEngine::INVAILD_AUdio_ID; //是否循环 _loopEnabled = false; //音量大小 _volume = 1.0f; // _duration = AudioEngine::TIME_UNKNowN; //更新间隔 _timeRatio = 0.0f; //更新进度条 _updateTimeSlIDer = true; //字体路径 std::string FontfilePath = "Fonts/arial.ttf"; //当前Size auto layerSize = this->getContentSize(); //play按钮,第一个参数是按钮名称,第二个参数是回调函数,在触摸结束后响应 auto playItem = Textbutton::create("play",[&](Textbutton* button) { //判断ID是否为INVAILD_AUTIO_ID if(_audioID == AudioEngine::INVAILD_AUdio_ID) { //播放音乐,第一个参数音乐文件路径,第二个参数,是否循环播放,第三个参数,音量,跟进去发现函数返回一个int值,值为0 _audioID = AudioEngine::play2d("background.mp3",_loopEnabled,_volume); log("_audioID = %d",_audioID);//打印0,即unordered_map的对象个数 log("INVAILD_AUdio_ID = %d",AudioEngine::INVAILD_AUdio_ID);//打印-1 //如果ID不等于AudioEngine::INVAILD_AUdio_ID,执行以下代码 if(_audioID != AudioEngine::INVAILD_AUdio_ID) { //设置按钮被按下,设置Lable字体颜色为灰色 button->setEnabled(false); //如果音乐播放完毕的回调函数 AudioEngine::setFinishCallback(_audioID,[&](int ID,const std::string& filePath) { //重新恢复ID值为-1 _audioID = AudioEngine::INVAILD_AUdio_ID; ((Textbutton*)_playItem)->setEnabled(true);//设置按钮为非触摸状态,即没有被按下,按钮字体颜色为White _timeRatio = 0.0f;//更新时间间隔为0 ((SlIDerEx*)_timeSlIDer)->setRatio(_timeRatio);//设置进度比 }); } } }); _playItem = playItem;//将当前playItem赋值给_playItem,这一步在初始化时执行,先于触摸playItem前执行 playItem->setposition(layerSize.wIDth*0.3f,layerSize.height*0.7f); addChild(playItem); //停止按钮 auto stopItem = Textbutton::create("stop",[&](Textbutton* button){ if(_audioID != AudioEngine::INVAILD_AUdio_ID) { AudioEngine::stop(_audioID); _audioID = AudioEngine::INVAILD_AUdio_ID; ((Textbutton*)_playItem)->setEnabled(true);//停止按钮按下,play按钮字体颜色变为White } }); stopItem->setposition(layerSize.wIDth*0.7f,layerSize.height*0.7f); addChild(stopItem); //暂停按钮 auto pauseItem = Textbutton::create("pause",[&](Textbutton* button){ if(_audioID != AudioEngine::INVAILD_AUdio_ID) { AudioEngine::pause(_audioID); } }); pauseItem->setposition(layerSize.wIDth*0.3f,layerSize.height*0.6f); addChild(pauseItem); //恢复播放按钮 auto resumeItem = Textbutton::create("resume",[&](Textbutton* button){ if(_audioID != AudioEngine::INVAILD_AUdio_ID) { AudioEngine::resume(_audioID); } }); resumeItem->setposition(layerSize.wIDth*0.7f,layerSize.height*0.6f); addChild(resumeItem); //是否循环播放 auto loopItem = Textbutton::create("enable-loop",[&](Textbutton* button){ _loopEnabled = !_loopEnabled;//取非,使_loopEnabled循环 if(_audioID != AudioEngine::INVAILD_AUdio_ID) { AudioEngine::setLoop(_audioID,_loopEnabled);//设置是否循环 } //设置循环播放按钮字体内容 if(_loopEnabled) { button->setString("disable-loop"); }else{ button->setString("enable-loop"); } }); loopItem->setposition(layerSize.wIDth*0.3f,layerSize.height*0.5f); addChild(loopItem); //加载缓冲 auto uncacheItem = Textbutton::create("uncache",[&](Textbutton* button){ AudioEngine::uncache("background.mp3"); _audioID = AudioEngine::INVAILD_AUdio_ID; ((Textbutton*)_playItem)->setEnabled(true);//设置play按钮为非触摸状态 }); uncacheItem->setposition(layerSize.wIDth*0.7f,layerSize.height*0.5f); addChild(uncacheItem); //声音进度条 auto volumeSlIDer = SlIDerEx::create(); volumeSlIDer->setPercent(100); volumeSlIDer->setCallBack([&](SlIDerEx* sender,float ratio,SlIDerEx::touchEvent event){ _volume = ratio;//获取音量值 if(_audioID != AudioEngine::INVAILD_AUdio_ID) { //设置音量 AudioEngine::setVolume(_audioID,_volume); } }); volumeSlIDer->setposition(Vec2(layerSize.wIDth*0.5f,layerSize.height*0.35f)); addChild(volumeSlIDer); //时间进度条 auto timeSlIDer = SlIDerEx::create(); //参数引用类对象,参数传递在触摸事件中 timeSlIDer->setCallBack([&](SlIDerEx* sender,SlIDerEx::touchEvent event){ switch (event) { case SlIDerEx::touchEvent::MOVE: case SlIDerEx::touchEvent::DOWN: _updateTimeSlIDer = false;//按钮和移动状态下,不更新时间进度条 break; case SlIDerEx::touchEvent::UP://抬起 if(_audioID != AudioEngine::INVAILD_AUdio_ID && _duration != AudioEngine::TIME_UNKNowN) { //设置当前时间进度条的进度 AudioEngine::setCurrentTime(_audioID,_duration*ratio); } break; case SlIDerEx::touchEvent::CANCEL: _updateTimeSlIDer = true;//取消动作,继续更新进度条 break; default: break; } }); timeSlIDer->setposition(Vec2(layerSize.wIDth*0.5f,layerSize.height*0.25f)); addChild(timeSlIDer); _timeSlIDer = timeSlIDer; //音量标签 auto volumeSlIDerPos = volumeSlIDer->getposition(); auto slIDerSize = volumeSlIDer->getContentSize(); auto volumeLabel = Label::createWithTTF("volume:",FontfilePath,20); volumeLabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE_RIGHT); volumeLabel->setposition(volumeSlIDerPos.x - slIDerSize.wIDth/2,volumeSlIDerPos.y); addChild(volumeLabel); //时间标签 auto timeSlIDerPos = timeSlIDer->getposition(); auto timeLabel = Label::createWithTTF("time:",20); timeLabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE_RIGHT); timeLabel->setposition(timeSlIDerPos.x-slIDerSize.wIDth/2,timeSlIDerPos.y); addChild(timeLabel); //每0.1秒更新帧 this->schedule(CC_CALLBACK_1(AudioControlTest::update,this),0.1f,"update_key"); bRet = true; }while(0); return bRet;}voID AudioControlTest::update(float dt){ //如果有音乐播放 if(_audioID != AudioEngine::INVAILD_AUdio_ID) { //并且时间未知 if(_duration == AudioEngine::TIME_UNKNowN) { //设置时间间隔 _duration = AudioEngine::getDuration(_audioID); } if(_duration != AudioEngine::TIME_UNKNowN) { //如果时间间隔不为TIME_UNKNowN,获取当前的播放时间 auto time = AudioEngine::getCurrentTime(_audioID); _timeRatio = time / _duration;//计算时间进度比 if(_updateTimeSlIDer)//如果更新进度条为true { ((SlIDerEx*)_timeSlIDer)->setRatio(_timeRatio);//设置时间进度条的进度 } } }}AudioControlTest::~AudioControltest(){ }std::string AudioControlTest::subTitle() const{ return "audio control test";}bool PlaySimultaneouslyTest::init(){ bool bRet = false; do{ CC_BREAK_IF(!BaseTest::init()); char text[36]; int tmp = 81; //获取音乐文件 for(int index = 0; index < TEST_COUNT;++index) { sprintf(text,"FX0%d.mp3",tmp+index); _files[index] = text; } //统计正在播放数量 _playingcount = 0; //创建播放按钮,回调函数的参数button在Textbutton的触摸事件中,传递的是this对象,即当前playItem对象 auto playItem = Textbutton::create("play-simultaneously",[&](Textbutton* button){ int audioID; _playingcount = 0; //设置按钮为触摸状态,即按下按钮 button->setEnabled(false); //获取当前时间,返回今天当前秒和微秒的值 auto startTime = utils::gettime(); for(int index = 0; index < TEST_COUNT; ++index) { //播放_files里的音乐 audioID = AudioEngine::play2d(_files[index]); if(audioID != AudioEngine::INVAILD_AUdio_ID) { //正在播放增加1 _playingcount += 1; //播放完毕的回调函数 AudioEngine::setFinishCallback(audioID,const std::string& filePath){ //正在播放减1 _playingcount -= 1; //如果正在播放的数量小于等于-1,设置播放按钮为true,即未按下状态 if(_playingcount <= 0) { ((Textbutton*)_playItem)->setEnabled(true); } }); }else//如果ID等于-1,则没有音乐文件播放,或播放音乐文件失败 { log("%s,%d,Fail to play file:%s",__file__,__liNE__,_files[index].c_str()); } } //打印播放的时长 log("diff time:%lf",utils::gettime() - startTime); }); //设置像素级坐标 playItem->setnormalizedposition(Vec2(0.5f,0.5f)); this->addChild(playItem); _playItem = playItem; bRet = true; }while(0); return bRet;}PlaySimultaneouslyTest::~PlaySimultaneouslytest(){ }std::string PlaySimultaneouslyTest::subTitle() const{ return "PlaySimultaneously Test";}bool AudioProfileTest::init(){ bool bRet = false; do{ CC_BREAK_IF(!BaseTest::init()); char text[30]; _files[0] = "background.mp3";#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC _files[1] = "background.caf";#else _files[1] = "background.ogg";#endif std::string FontfilePath = "Fonts/arial.ttf"; _minDelay = 1.0f;//两个声音的最小时间间隔 _time = 0.0f; _audioProfile.name = "AudioProfileTest";//name不可为空 _audioProfile.maxInstances = 3;//音乐文件数量 _audioProfile.minDelay = 1.0;//两个声音的最小时间间隔 Vec2 pos(0.5f,0.7f); for(int index = 0; index < file_COUNT; ++index) { sprintf(text,"play %s",_files[index].c_str()); auto playItem = Textbutton::create(text,[&](Textbutton* button){ int index = button->getTag(); //播放文件,参数1:文件路径,参数2:不循环播放,参数3:音量,参数4:AudioProfile对象,设置相关配置 auto ID = AudioEngine::play2d(_files[index],false,1.0f,&_audioProfile); if(ID != AudioEngine::INVAILD_AUdio_ID) { _time = _minDelay; _audioCount += 1; char show[30]; sprintf(show,"audio count:%d",_audioCount); _showLabel->setString(show); //播放完毕回调事件 AudioEngine::setFinishCallback(ID,const std::string& filePath){ _audioCount = -1; char show[30]; sprintf(show,_audioCount); _showLabel->setString(show); }); } }); playItem->setTag(index); playItem->setnormalizedposition(pos); this->addChild(playItem); pos.y -= 0.15f; } Vec2 origin = Director::getInstance()->getVisibleOrigin(); Size winSize = Director::getInstance()->getVisibleSize(); auto profileInfolabel = Label::createWithTTF("AudioProfile Info:\n max instance:3 \n minimum delay:1.0",20); profileInfolabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE_left); profileInfolabel->setposition(Vec2(origin.x,origin.y+winSize.height*0.65f)); addChild(profileInfolabel); _audioCount = 0; //初始化_showLabel对象 _showLabel = Label::createWithTTF("audio count:0",20); _showLabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE_left); _showLabel->setposition(Vec2(origin.x,origin.y+winSize.height*0.5f)); addChild(_showLabel); //初始化timeSlIDer对象 auto timeSlIDer = SlIDerEx::create(); timeSlIDer->setEnabled(false); timeSlIDer->setnormalizedposition(pos); addChild(timeSlIDer); _timeSlIDer = timeSlIDer; this->schedule(CC_CALLBACK_1(AudioProfileTest::update,0.05f,"update_key"); bRet = true; }while(0); return bRet;}voID AudioProfileTest::update(float dt){ if(_time > 0.0f) { _time -= dt; //设置进度比 ((SlIDerEx*)_timeSlIDer)->setRatio(_time / _minDelay); }}AudioProfileTest::~AudioProfiletest(){ }std::string AudioProfileTest::subTitle() const{ return "AudioProfile test";}bool InvalIDAudiofileTest::init(){ bool bRet = false; do{ CC_BREAK_IF(!BaseTest::init()); auto playItem = Textbutton::create("play unsupported media type",[&](Textbutton* button){#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC AudioEngine::play2d("background.ogg");#elif CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 AudioEngine::play2d("background.caf");#endif }); playItem->setnormalizedposition(Vec2(0.5f,0.6f)); this->addChild(playItem); //播放不存在的音乐文件,查看控制台 auto playItem2 = Textbutton::create("play not-existent file",[&](Textbutton* button){ AudioEngine::play2d("not-existent file.mp3"); }); playItem2->setnormalizedposition(Vec2(0.5f,0.4f)); this->addChild(playItem2); bRet = true; }while(0); return bRet;}InvalIDAudiofileTest::~InvalIDAudiofiletest(){ }std::string InvalIDAudiofileTest::subTitle() const{ return "InvalIDAudiofile test";}//播放比较大的音乐文件bool LargeAudiofileTest::init(){ bool bRet = false; do{ CC_BREAK_IF(!BaseTest::init()); auto playItem = Textbutton::create("play large audio file",[&](Textbutton* button){ AudioEngine::play2d("LuckyDay.mp3"); }); playItem->setnormalizedposition(Vec2::ANCHOR_MIDDLE); this->addChild(playItem); bRet = true; }while(0); return bRet;}LargeAudiofileTest::~LargeAudiofiletest(){ }std::string LargeAudiofileTest::subTitle() const{ return "LargeAudiofile Test";}#endif总结
以上是内存溢出为你收集整理的Cocos2d-x3.3RC0 Cpp-test分析之NewAudioEngineDemo全部内容,希望文章能够帮你解决Cocos2d-x3.3RC0 Cpp-test分析之NewAudioEngineDemo所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)