Reputation: 21
I am trying to run music in a game, but for whatever reason, the file refuses to play entirely. It's a 7 second track, but only the first second or so plays and then I'm given silence. I also programmed this in such a way that it should loop, but it does not do so. Can anyone tell me what I'm doing wrong? Again, the file DOES play, but only the first second and only once.
sf::Music music;
if (!music.openFromFile("data/sounds/music.wav")){
std::cout << "Error...";
}
else{
music.setLoop(true);
music.setVolume(50);
music.play();
}
Upvotes: 2
Views: 1567
Reputation: 1779
The music will only play as long as the sf::Music object remains in scope. If the sf::Music object is declared in a method, it is destructed at the end of that method, and the music will stop too.
Give your sf::Music instance class scope; It will keep playing until the class goes out of scope or .stop()/.pause() is called.
So instead of:
class MyClass {
public:
void playMahJam() {
sf::Music jam; // Will be destructed at end of method
if (!music.openFromFile("data/sounds/music.wav")){
std::cout << "Error..." << std::endl;
}
else{
music.setLoop(true);
music.setVolume(50);
music.play();
}
} // end playMahJam()
};
Try:
class MyClass {
public:
void playMahJam() {
if (!music.openFromFile("data/sounds/music.wav")){
std::cout << "Error..." << std::endl;
}
else{
music.setLoop(true);
music.setVolume(50);
music.play();
}
} // end playMahJam()
private:
sf::Music jam;
};
Upvotes: 1