Using SFML, I want to be able to play multiple music files at once.
My code currently looks like this:
#include <SFML/Audio.hpp>
#include <iostream>
#include <thread>
#include <vector>
#include <semaphore.h>
using namespace std;
void playMusic(const string &filename, float volume = 50.0f, float pitch = 1.0f) {
sf::Music music;
if (!music.openFromFile(filename)) {
cerr << "Failed to load " << filename << endl;
return;
}
music.setPitch(pitch);
music.setVolume(volume);
music.play();
while (music.getStatus() == sf::Music::Playing) {
this_thread::sleep_for(chrono::milliseconds(100));
}
music.stop();
}
int main() {
vector<string> musicFiles = {"../res/test.wav", "../res/test.mp3"};
vector<thread> threads;
sem_t sem;
sem_init(&sem, 0, 1);
for (size_t i = 0; i < musicFiles.size(); i++) {
sem_wait(&sem);
string filename = musicFiles[i];
float pitch = 1.0f + (i * 0.1f);
threads.emplace_back([pitch, filename, &sem]() {
playMusic(filename, 50.0f, pitch);
sem_post(&sem);
});
}
for (auto &thread: threads) {
thread.join();
}
return 0;
}
For each music file, the application makes a new thread and starts playing the file on that thread.
However, when I run the application, only one music file starts playing at a time.
Is there any way to fix this and relocate these music objects to the heap, or is this truly the limit of SFML?