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

Author Topic: No music when trying to call a method from a class.  (Read 2629 times)

0 Members and 1 Guest are viewing this topic.

Sixoul

  • Newbie
  • *
  • Posts: 17
    • View Profile
No music when trying to call a method from a class.
« on: October 21, 2013, 09:46:25 pm »
So right now I'm trying to get a basic idea of how to set things up.
game.cpp
#include "stdafx.h"
#include "Game.h"
#include "GameMusic.h"

int main()
{
    // create the window
    sf::RenderWindow gamescreen(sf::VideoMode(800, 600), "Legend of Link");
       
        // create texture and sprite
        sf::Texture texture;
        sf::Sprite sprite;

        // play the audio
        GameMusic ingamemusic;
        ingamemusic.PlayMusic();


        if (!texture.loadFromFile("res/graphics/Link.png"))
{
    // error...
}
        else
                sprite.setTexture(texture);

    // run the program as long as the window is open
    while (gamescreen.isOpen())
    {
        // check all the window's events that were triggered since the last iteration of the loop
        sf::Event event;
        while (gamescreen.pollEvent(event))
        {
            // "close requested" event: we close the window
            if (event.type == sf::Event::Closed)
                        {
                                //music.StopMusic();
                gamescreen.close();
                        }
        }

        // clear the window with black color
        gamescreen.clear(sf::Color::Black);

        // draw everything here...
        // gamescreen.draw(...);
                gamescreen.draw(sprite);

        // end the current frame
        gamescreen.display();
    }

    return 0;
}

GameMusic.cpp
#include "GameMusic.h"

int GameMusic::PlayMusic()
{
        sf::Music music;
        if (!music.openFromFile("res/audio/music/Vengeance.ogg"))
                return -1; // error
        music.setVolume(100);
        music.play();
}

So when I take the PlayMusic() and put it into Game.cpp it runs fine. But when I try to call the method for it to do the same thing it doesn't play the music. Am I forgetting something? I feel like it would be something super simple too.

Ixrec

  • Hero Member
  • *****
  • Posts: 1241
    • View Profile
    • Email
Re: No music when trying to call a method from a class.
« Reply #1 on: October 21, 2013, 09:51:01 pm »
You forgot how scope works.  If you create a variable inside a function, it gets destroyed at the end of the function.  This is basic C++.

You need to make the sf::Music instance a member of the class, or a static variable in the function.

Sixoul

  • Newbie
  • *
  • Posts: 17
    • View Profile
Re: No music when trying to call a method from a class.
« Reply #2 on: October 21, 2013, 10:30:49 pm »
Thanks. I knew it was something simple.

 

anything