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

Author Topic: Not playing sound from function  (Read 2611 times)

0 Members and 1 Guest are viewing this topic.

robvleugel

  • Newbie
  • *
  • Posts: 29
    • View Profile
Not playing sound from function
« on: May 18, 2012, 09:33:49 pm »
Hello,

I am having some problems with the sfml audio package. My code to load the sound is the code below:

#include <SFML\System.hpp>
#include <SFML\Audio.hpp>

void Playsound()
{
        sf::Sound sound;
        sf::SoundBuffer sbuffer;
        sbuffer.loadFromFile("boom.wav");
        sound.setBuffer(sbuffer);
        sound.play();
}

int main()
{
        Playsound();
        sf::Clock clock; while(clock.getElapsedTime().asSeconds() < 5) {}
        return 0;
}
 

If I move the code from Playsound() to main it works. It doesn't work from within a function.
I mean this makes it hard to play a sound isn't it, what am I doing wrong?
« Last Edit: May 19, 2012, 07:57:39 am by Laurent »

robvleugel

  • Newbie
  • *
  • Posts: 29
    • View Profile
Re: Not playing sound from function
« Reply #1 on: May 18, 2012, 09:48:05 pm »
I guess I already figured it out.
Because I create the sf:Sound and sf::SoundBuffer within the function, these are local variables and are removed as soon as the code has been executed. Even while play() will play within a separate thread, this code will reference to a SoundBuffer that is not accessible, am I right?

So for my code to work I just have to make the sf::Sound(Buffer) objects part of the class that uses them.

Sorry for my post, guess I should've been more patient.

Greetings,
Rob


robvleugel

  • Newbie
  • *
  • Posts: 29
    • View Profile
Re: Not playing sound from function
« Reply #2 on: May 18, 2012, 10:37:55 pm »
Hm I am still getting problems.
For instance, take the class below:

class AudioManager
{
private:
        sf::SoundBuffer m_soundbuffer;
        sf::Sound m_sound;

public:

        void Init();
        void PlaySound() {m_sound.play();}

};

void AudioManager::Init()
{
m_soundbuffer.loadFromFile("mysound.wav");
m_sound.setBuffer(soundbuffer);
}
 

This gives me a crash when I try to use it.
What am I doing wrong this time?


Kind regards,
Rob
« Last Edit: May 19, 2012, 07:58:04 am by Laurent »

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32504
    • View Profile
    • SFML's website
    • Email
Re: Not playing sound from function
« Reply #3 on: May 19, 2012, 07:59:01 am »
There's probably a mistake in the code that you don't show.

And learn how to use the debugger, it exists exactly to answer this kind of questions ;)
Laurent Gomila - SFML developer

robvleugel

  • Newbie
  • *
  • Posts: 29
    • View Profile
Re: Not playing sound from function
« Reply #4 on: May 20, 2012, 04:38:33 pm »
It was indeed an error in the code not being shown here, a realy stupid one so I'm glad I didn't post it :)
Thanks for the help anyway!


Kind regards,
Rob