Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Method inside of a class isn't playing the music  (Read 2710 times)

0 Members and 1 Guest are viewing this topic.

JPO

  • Newbie
  • *
  • Posts: 2
    • View Profile
    • Email
Method inside of a class isn't playing the music
« 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?


« Last Edit: May 10, 2017, 03:33:46 pm by Laurent »

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32498
    • View Profile
    • SFML's website
    • Email
Re: Method inside of a class isn't playing the music
« Reply #1 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.
Laurent Gomila - SFML developer

JPO

  • Newbie
  • *
  • Posts: 2
    • View Profile
    • Email
Re: Method inside of a class isn't playing the music
« Reply #2 on: May 10, 2017, 04:10:32 pm »
Thanks man, now I understand how this class works :).