Hi all!
I didn’t find a built in way to fade out the background music (Cocos2d-X 2.2.0), so I started building a simple audio manager singleton class. The idea was that this class should have a function that lower the volume by 10, and by running this over and over with a delay the music would fade out.
The problem I face is that when I try to schedule the function it is never run. The only way I could get the function scheduled is by adding my audio manager class as a child of what’s currently displayed.
Here is AudioManager.h:
<pre><code class=“cpp”>
#include “cocos2d.h”
class AudioManager : public cocos2d::CCNode
{
private:
AudioManager();
virtual bool init();
static AudioManager\* m\_mySingleton;
protected:
void fadeOutBackgroundMusicHelper(cocos2d::CCTime dt);
public:
static AudioManager* getShared();
void fadeOutBackgroundMusic();
};
</code></pre>
and AudioManager.cpp:
<pre><code class=“cpp”>
#include “AudioManager.h”
#include “SimpleAudioEngine.h”
USING_NS_CC;
AudioManager* AudioManager::m_mySingleton = NULL;
AudioManager::AudioManager() {}
AudioManager* AudioManager::getShared() {
if(NULL == m_mySingleton) {
m_mySingleton = new AudioManager();
m_mySingleton->init();
}
return m_mySingleton;
}
bool AudioManager::init() {
if(!CCNode::init()) {
return false;
}
return true;
}
void AudioManager::fadeOutBackgroundMusic() {
this->schedule(schedule_selector(AudioManager::fadeOutBackgroundMusicHelper), 0.1, 9, 0);
}
void AudioManager::fadeOutBackgroundMusicHelper(CCTime dt) {
CocosDenshion::SimpleAudioEngine *audioEngine = CocosDenshion::SimpleAudioEngine::sharedEngine();
float vol = audioEngine-\>getBackgroundMusicVolume();
CCLOG("volume: f", vol);
if(vol > 0.1) {
audioEngine~~>setBackgroundMusicVolume;
} else {
audioEngine~~>stopBackgroundMusic();
audioEngine~~>setBackgroundMusicVolume;
CCLOG (“Background music stopped”);
}
}
</pre>
The function is scheduled and the music is faded only if I add the object as a child the the current layer like this:
<pre>
AudioManager *am = AudioManager::getShared;
this~~>addChild(am);
am->fadeOutBackgroundMusic();
Thank you in advance