Yuri Kircovich
Yuri Kircovich

Reputation: 13

Can't get SFML Music to work

Okay, just a forewarning: I am really new to C++ and only began coding this year.

So, I have been trying to code this program to run in the console using the SFML libraries. I had problems in the past trying to get the libraries to work, but now I'm good. So, I have a function that plays music, but when I try to activate the function in the console I just get a return value of 0 and the console closes.

Relevant code:

void music ()
{
      system("CLS");

      sf::Music WorldOnFire;

      std::string musicInput;

      std::cout << "What would you like to listen to?" << std::endl;
      std::cout << "> Track 1 - \"I Don't Want to Set the World on Fire\" by The Ink Spots" << std::endl;
      std::cout << "> Back" << std::endl;

      std::getline(std::cin, musicInput);

      std::transform(musicInput.begin(), musicInput.end(), musicInput.begin(), ::toupper);
      musicInput.erase(std::remove(musicInput.begin(), musicInput.end(), ' '), musicInput.end());

      if (musicInput == "TRACK1" || musicInput == "TRACK1-\"IDON'TWANTTOSETTHEWORLDONFIRE\"" || musicInput == "TRACK1-\"IDON'TWANTTOSETTHEWORLDONFIRE\"BYTHEINKSPOTS" || musicInput == "\"IDON'TWANTTOSETTHEWORLDONFIRE\"" || musicInput == "IDON'TWANTTOSETTHEWORLDONFIRE")
      {
          if (!WorldOnFire.openFromFile("WorldOnFire.ogg"))
          {
               std::cout << "Could not open file. File corrupted or missing." << std::endl;
               std::cin.ignore();
               music();
          }
          WorldOnFire.play();
      }

      else if (musicInput == "BACK")
      {
          system("CLS");
          activitypage ();
      }
}

Here is all the code, with omissions for personal reasons. Source

Upvotes: 1

Views: 958

Answers (1)

Hiura
Hiura

Reputation: 3530

WorldOnFire.play(); is non blocking. Therefore your program will terminate before any sound is actually played.

You need to add some kind of loop in your application. It can be as simple as a greedy while(isPlaying):

while (WorldOnFire.getStatus() == sf::Music::Playing);

or a bit more energy-efficient:

sf::sleep(WorldOnFire.getDuration() - WorldOnFire.getPlayingOffset());

Upvotes: 2

Related Questions