c++ - 无法让 SFML 音乐工作

标签 c++ c++11 sfml

好吧,只是一个预警:我是 C++ 的新手,今年才开始编码。

因此,我一直在尝试使用 SFML 库编写此程序以在控制台中运行。过去我在尝试让库正常工作时遇到过问题,但现在我很好了。所以,我有一个播放音乐的功能,但是当我尝试在控制台中激活该功能时,我只得到一个返回值 0 并且控制台关闭。

相关代码:

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 ();
      }
}

这里是全部代码,个人原因有遗漏。 Source

最佳答案

WorldOnFire.play(); 是非阻塞的。因此,您的程序将在实际播放任何声音之前终止。

您需要在您的应用程序中添加某种循环。它可以像贪婪的 while(isPlaying) 一样简单:

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

或者更节能一点:

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

关于c++ - 无法让 SFML 音乐工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27679668/

相关文章:

linux - 使用 mmap() 在进程之间共享 std::map

c++ - 编译有效,启动不是 - "standard path"?

c++ - 将 SFML 网络与 SDL2 结合使用

c++ - 使用路径变量时包含不扩展的路径

c++ - 什么情况下会声明一个非引用、非指针类型的函数参数const?

c++ - Google OR-Tools 使用什么近似 TSP 算法?

c++ - 关于 std::future 的编译错误

c++ - 避免手动创建 lambda 来包装对 new[]: 的调用,以用作 std::generate 中的生成器函数

c++ - map 的 std::for_each() 给出无效的初始化错误

c++ - 为什么 SFML 中的 sf::Clock 会自行重置?