有没有一种简单的方法可以使用 SFML 在后台线程中播放声音

Is there a simple way to play a sound in a background thread using SFML

我正在尝试在我的 GUI 应用程序的后台线程中播放歌曲,这样歌曲就不会阻塞 GUI 线程。有没有一种简单的方法可以使用 std::thread 或 SFML 线程来做到这一点?

我已经尝试为此使用 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

}

在 SFML 中,您需要有一个有效的 sf::Sound 或 sf::Music 才能播放音乐,当该变量被销毁时,您将不再具有对该对象的有效引用您发布的代码应该是这样的:

#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 行语句是否始终使用括号,我知道这是允许的,但它会让您在以后进行故障排除时更轻松。