Music Fader for Cocos2dx

Here’s a class for fading music in Cocos2dx 2.x using the SimpleAudioEngine. Seems like this should be a basic function of the SimpleAudioEngine itself, but this is pretty easy to use, just run it on any CCNode like any other action:

runAction(MusicFade::create(1.0f, 0.0f, true));

Copy and paste from below, or here’s a zip with the files.

#include "MusicFade.h"
#include "SimpleAudioEngine.h"

using namespace cocos2d;
using namespace CocosDenshion;

MusicFade::MusicFade()
{
    m_initialVal = 0;
    m_targetVal = 0;
}

MusicFade* MusicFade::create(float duration, float volume, bool pauseOnComplete)
{
    MusicFade *pAction = new MusicFade();
    pAction->initWithDuration(duration, volume, pauseOnComplete);
    pAction->autorelease();

    return pAction;
}

bool MusicFade::initWithDuration(float duration, float volume, bool pauseOnComplete)
{
    if (CCActionInterval::initWithDuration(duration))
    {
        m_targetVal = volume;
        m_bPauseOnComplete = pauseOnComplete;
        return true;
    }

    return false;
}

void MusicFade::update(float time)
{
    float vol = m_initialVal + time*(m_targetVal - m_initialVal);
    SimpleAudioEngine::sharedEngine()->setBackgroundMusicVolume(vol);

}

void MusicFade::startWithTarget(CCNode *pTarget)
{
    CCActionInterval::startWithTarget( pTarget );
    m_initialVal = SimpleAudioEngine::sharedEngine()->getBackgroundMusicVolume();
}

void MusicFade::stop(void)
{
    if(m_bPauseOnComplete) SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
    CCActionInterval::stop();
}
#ifndef __MusicFade__
#define __MusicFade__

#include "cocos2d.h"

class MusicFade : public cocos2d::CCActionInterval
{
public:
    MusicFade();

    static MusicFade* create(float d, float volume, bool pauseOnComplete = false );
    bool initWithDuration(float d, float volume, bool pauseOnComplete );

    virtual void startWithTarget(cocos2d::CCNode *pTarget);
    virtual void update(float time);
    virtual void stop(void);

protected:
    float m_targetVal;
    float m_initialVal;
    bool m_bPauseOnComplete;
};

#endif /* defined(__MusicFade__) */

2 thoughts on “Music Fader for Cocos2dx

  1. Pingback: [cocos2d-x]WindowsでAndroidアプリ開発日誌7:アプリ実装の工夫や躓きを包み隠さず振り返る

Leave a Reply