0

my goal is to call a function after background music ends in cocos2dx.

playing background music using this code

    CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("shortSound.wav",false);

and need to call my Function

void GamePlay::gameLevelEnds()

when the background sound ends.

Anand
  • 1,129
  • 7
  • 29

2 Answers2

0

There are no direct interfaces to do in cocos2dx but you can just find the duration of sound file and run an action with delay of duration followed by callback function.

Vikas Patidar
  • 42,865
  • 22
  • 93
  • 106
0

This is possible.

General Solution

float duration = 10.0f;
CCSequence *soundSequence = CCSequence::create(CCDelayTime::create(duration),CCCallFunc::create(this, callfunc_selector(GamePlay::soundEndedAction)),NULL);
this->runAction(soundSequence);

method to monitor sound end action

void GamePlay::soundEndedAction(){
    CCLOG("+++sound ended+++%s",__PRETTY_FUNCTION__);

}

//======== For only iOS Platform below solution can be applied.=====//

I created a method in "AppController.h"

-(void)backgroundFinished;

and in "AppController.mm"

-(void)backgroundFinished
{
    NSLog(@"+++Music ended....+++");
    CocosDenshion::SimpleAudioEngine::sharedEngine()->stopBackgroundMusic();
}

and added below lines in init method of "SimpleAudioEngine_objc.m" file

-(id) init
{
    if((self=[super init])) {
        am = [CDAudioManager sharedManager];
        //=======added this line=========//
        [am setBackgroundMusicCompletionListener:[[UIApplication sharedApplication]delegate] selector:@selector(backgroundFinished)];//28 Aug 2014
        //===============================//
        soundEngine = am.soundEngine;
        bufferManager = [[CDBufferManager alloc] initWithEngine:soundEngine];
        mute_ = NO;
        enabled_ = YES;
    }
    return self;
}

now in my "GamePlay.cpp" class I scheduled update method

void GamePlay::update(float dt)
{       
    if(!CocosDenshion::SimpleAudioEngine::sharedEngine()->isBackgroundMusicPlaying())
    {
        CCLOG("+++Background Music Ended+++ :%d",CocosDenshion::SimpleAudioEngine::sharedEngine()->isBackgroundMusicPlaying());
        //Take neccessory actions
    }
}
Anand
  • 1,129
  • 7
  • 29