Search code examples
c++eventssfml

Check if music has ended, OnStopped?


Is it possible to make SFML 1.6 handle end of music by itself? Currently I have this:

//in music.cpp
music.Play()

//in main.cpp
//on every frame check for end of music
if(music.getStatus() == Sound::Stopped)
    loadNextMusicFile();

Isn't there a way in SFML to just say, "Play until music stopped, then load the next," without implementing this yourself? Or at least a more "elegant" way of noticing when the music stopped (like an OnStopped event)?


Solution

  • If you look at the code from Music.cpp

    bool Music::OnGetData(SoundStream::Chunk& data)
    {
        Lock lock(myMutex);
    
        // Fill the chunk parameters
        data.Samples   = &mySamples[0];
        data.NbSamples = myFile->Read(&mySamples[0], mySamples.size());
    
        // Check if we have reached the end of the audio file
        return data.NbSamples == mySamples.size();
    }
    

    You see that it will return false when its at the end of the file.

    So what you want to do is subclass sf::Music. e.g.

    class MyMusic : public sf::Music
    {
       bool OnGetData(SoundStream::Chunk& data)
       {
           bool running = sf::Music::OnGetData(data);
           if(!running)
              OnMusicEnd();
           return running;
       }
    public:
       void OnMusicEnd()
       {
           // ...
       }
    
    };