Search code examples
cocos2d-xcocos2d-x-3.0

How to know if a music file has finished playing?


In cocos2d-x, you can play music by doing the following:

auto audio = SimpleAudioEngine::getInstance();

// set the background music and play it just once.
audio->playBackgroundMusic("mymusic.mp3", false);

But how do we know if the music has finished playing ? The game could be interrupted by a phone call (triggering other code that pauses the game and the music) or paused by the user.

Is there anyway to know if the file has finished playing ? I know we can keep some kind of timer to keep track of the duration the song has been playing but that seems hacky, and this is a common use case, especially if we want to queue a playlist.


Solution

  • It looks like you'll have to test audio->isBackgroundMusicPlaying() in your update() methods.

    There ought to be a delegate, or some other kind of callback, which will tell you such things. I guess you could subclass SimpleAudioEngine to add this.

    EDIT There is experimental::AudioEngine which offers a didFinishCallback:

    static void setFinishCallback(int audioID, const std::function<void(int, const std::string &)> &callback);
    

    However you need to be aware that I don't think it supports all platforms, so use with caution.