我正在尝试在GUI应用程序的后台线程中播放歌曲,以便歌曲不会阻止GUI线程。有没有一种简单的方法可以使用std :: thread或SFML Threads?
我已经尝试过使用std :: thread,但是当我调用my_thread.join()
时它仍会阻止GUI线程。
以下是我想要做的一个例子:
#include <thread>
#include <SFML/Audio.hpp>
#include <unistd.h>
#include <iostream>
void func() {
sf::Music music;
music.openFromFile("mysong.wav");
music.play();
// if I don't have usleep here the function exits immediately
// why is that exactly???
usleep(100000000);
}
int main() {
std::thread my_thread(func);
my_thread.join();
// this is where I would process events/build windows in GUI
while(1)
std::cout << "here"; // <--- Want this to run while song plays
}
答案 0 :(得分:1)
#include <SFML/Audio.hpp>
#include <unistd.h>
#include <iostream>
class CAudio
{
sf::Music music;
public:
void func()
{
music.openFromFile("mysong.wav");
music.play();
}
sf::Status getStatus()
{
return music.getStatus();
}
}
int main() {
CAudio my_music;
my_music.func();
// http://www.sfml-dev.org/documentation/2.0/SoundSource_8hpp_source.php
while(my_music.getStatus() == sf::Status::Playing)
{
std::cout << "here"; // <--- Want this to run while song plays
}
}
另外,总是使用括号,无论它的1行语句总是使用括号,我知道它是允许的,但是当你稍后进行故障排除时它会让你的生活更轻松。