SFML starting a new song once another song is complete

Viewed 59
#include <iostream>
#include <SFML/Window.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Audio/Music.hpp>


using namespace std;

int main (){

    sf::RenderWindow window(sf::VideoMode(800, 600), "My Window");

        sf::Music music;
        if (!music.openFromFile("Music/Fallen-Down.ogg"))
            return EXIT_FAILURE;
    music.play();

//  if(!music.openFromFile("Music/CORE.ogg"))
//      return EXIT_FAILURE;

    while (window.isOpen()){
            // check all the window's events that were triggered since the last iteration        of the loop
            sf::Event event;
            while (window.pollEvent(event)) {
             // "close requested" event: we close the window
            if (event.type == sf::Event::Closed)
                         window.close();                
            }
        
        if(music.getStatus() == 0)
            music.play();
    
        window.clear(sf::Color(255, 255, 255, 0));

        window.display();

        }
    return EXIT_SUCCESS;
}

I have my basic window which opens and plays a song. All I want to do is play the next song "CORE.ogg" when the first song "Fallen-Down"is finished playing. I have tried using the getStatus() function from the SFML Documentation which I believe returns an integer corresponding to the status of the song from an enum defined as

enum Status {Stopped, Paused, Playing}

I check which number it returns and if it returns 0 i was hoping it would play again. It's in the window loop so it should be checking at the end of every loop the status of the song...

1 Answers

If you want the music to play again, then you need to stop() the current music, even though it has come to its own end, because that will rewind the music back to the beginning.

if(music.getStatus() == sf::SoundSource::Status::Stopped)
{
    music.stop(); // rewind to beginning
    music.play();
}

BTW you should use sf::SoundSource::Status::Stopped rather than 0 as it may change value in a future version or on another platform.

If you want to play different music, you need to load it:

if(music.getStatus() == sf::SoundSource::Status::Stopped)
{
    music.openFromFile("Music/CORE.ogg");
    music.play();
}
Related