Wednesday, May 6, 2015

Cocos2dx: Pausing a sound after finite seconds

This is one way to play loop a sound and then pausing it after 15 secs. See green comments for explanation.

#include <SimpleAudioEngine.h>

bool HelloWorld::init()
    if ( !Layer::init() )
        return false;
    const char* sound = "audio/CanBomb.mp3";
    //create the sound and play loop it
    auto audio=CocosDenshion::SimpleAudioEngine::getInstance();
    int soundId = audio->playEffect(sound,true);//true: looping sound
    //create the action to delay 15 secs
    auto actionDelay = DelayTime::create(15);
    //create the action to pause sound
    auto callbackAudio = CallFunc::create([](){

    //create sequence putting in delay and pause action created above
    auto actionSequence = Sequence::create(actionDelay,callbackAudio, NULL);

    //run the action
    return true;

This is another way to do it:

#include <SimpleAudioEngine.h>

bool HelloWorld::init()
    if ( !Layer::init() )
        return false;
    const char* sound = "audio/CanBomb.mp3";
    //create the sound and play loop it
    auto audio=CocosDenshion::SimpleAudioEngine::getInstance();
    int soundId = audio->playEffect(sound,true);//true: looping sound

    this->schedule(schedule_selector(HelloWorld::StopSound), 15);
    return true;

//Declare it in header file as well:
void HelloWorld::StopSound(float dt){



//The header file
class HelloWorld : public cocos2d::Layer
    // there's no 'id' in cpp, so we recommend returning the class instance pointer
    static cocos2d::Scene* createScene();

    // implement the "static create()" method manually
    void StopSound(float dt);


No comments:

Post a Comment