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

Author Topic: Playing sound outside the main function doesn't work.  (Read 1229 times)

0 Members and 1 Guest are viewing this topic.

Kappa

  • Newbie
  • *
  • Posts: 4
  • yes
    • View Profile
Playing sound outside the main function doesn't work.
« on: November 13, 2022, 02:02:00 am »
I'm trying to make an audio manager that stores the pointers of sound buffer in a **map**.
Retrieving the sound buffer pointers and playing them works fine inside the main function.

But when you play a sound outside the main function, it doesn't. Even when the sound buffer still exists.

An example code that recreates this problem:

void say()
{
        sf::SoundBuffer buffer;
        buffer.loadFromFile("Assets/Audio/burp.wav");

        sf::Sound sound;
        sound.setBuffer(buffer);

        sound.play(); // Doesn't play the sound.
}

int main()
{
        say();
        // SFML window stuff...
}
 
   

kojack

  • Sr. Member
  • ****
  • Posts: 300
  • C++/C# game dev teacher.
    • View Profile
Re: Playing sound outside the main function doesn't work.
« Reply #1 on: November 13, 2022, 04:07:29 am »
When the end of the say function is reached, all local variables made in say are removed. This means the sound buffer and the sound are removed. So the sound is deleted nanoseconds after it starts playing.
Both the soundbuffer and sound must be kept alive for the duration of the sound.

Using pointers in a map as you mentioned is how I do it. But you need the sound stored as well, not just the sound buffer.

I use a map of strings (filenames) to sound buffer pointers and a vector of sound pointers. Each update I loop over the sounds checking if their status is sf::SoundSource::Stopped, in which case I delete them.

Kappa

  • Newbie
  • *
  • Posts: 4
  • yes
    • View Profile
Re: Playing sound outside the main function doesn't work.
« Reply #2 on: November 13, 2022, 05:17:52 am »
That really explains a lot, I didn't even notice that it was going out of scope and destroying the sound and soundbuffer after it called .play().

I created two manager that stores the sf::Sound and sf::SoundBuffer inside a map so that it would never be destroyed, unless deleted manually. This is also solves the issue of the variables going out of scope causing them to be destroyed.

Now it finally works!

Thank you!
« Last Edit: November 13, 2022, 05:46:52 am by IWasAllen »