SFML community forums

Help => Audio => Topic started by: JPO on May 10, 2017, 03:29:39 pm

Title: Method inside of a class isn't playing the music
Post by: JPO on May 10, 2017, 03:29:39 pm
Hello guys, I'm having some trouble understanding what's wrong with this code.


#include <SFML\Graphics.hpp>
#include <SFML\Audio\Sound.hpp>
#include <SFML\Audio\Music.hpp>
#include <iostream>

class MusicSample{
public:
        void PlayMusic();
};

void MusicSample::PlayMusic(){

        sf::Music mMusic;

        // Open it from an audio file
        if (!mMusic.openFromFile("battletoads_level1.ogg"))
        {
                // error...
        }
        // Change some parameters
        mMusic.setPosition(0, 1, 10); // change its 3D position
        mMusic.setPitch(2);               // increase the pitch
        mMusic.setVolume(50);         // reduce the volume
        mMusic.setLoop(true);         // make it loop

        // Play it
        mMusic.play();
}

int main(){

        sf::RenderWindow window(sf::VideoMode(300,300), "SFML");
        MusicSample music;
        music.PlayMusic();
        window.display();
        getchar();
        return 0;
};
 

It doesn't play any music, but if we paste the same code directly into the main method it works, it also works if we make mMusic a private member.

I come from a C# background and I'm not seeing a problem with this code.

So my question is what's the problem with this code?


Title: Re: Method inside of a class isn't playing the music
Post by: Laurent on May 10, 2017, 03:33:35 pm
The sf::Music object is local to the function, and thus is destroyed immediately after you start it. It must remain alive as long as it's playing, if you want to hear it.
Title: Re: Method inside of a class isn't playing the music
Post by: JPO on May 10, 2017, 04:10:32 pm
Thanks man, now I understand how this class works :).