SFML community forums

Help => Audio => Topic started by: Pvt.Derpy on November 29, 2018, 07:20:30 pm

Title: No compile errors, yet no sound.
Post by: Pvt.Derpy on November 29, 2018, 07:20:30 pm
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
        {
                if (gameState->mPlayerFireCooldown <= 0.0f)
                {
                        // ...
                       
                        sf::SoundBuffer w;
                        w.loadFromFile("../assets/shot.wav");
                        sf::Sound s;
                        s.setBuffer(w);
                        s.play();
                }
}

Seems normal. Isn't it? I've spent thetwo hours on google and couldn't find a solution.

Any ideas?

Thanks in advance.
Title: Re: No compile errors, yet no sound.
Post by: G. on November 29, 2018, 07:41:14 pm
Hey.
Your SoundBuffer and Sound are destroyed at the end of the scope they are declared in (like any local variable). In your code they are destroyed just after "s.play();" so it doesn't even have enough time for you to hear it.
Declare them somewhere else where their lifetime is longer.
Title: Re: No compile errors, yet no sound.
Post by: Pvt.Derpy on November 29, 2018, 08:08:41 pm
Hey.
Your SoundBuffer and Sound are destroyed at the end of the scope they are declared in (like any local variable). In your code they are destroyed just after "s.play();" so it doesn't even have enough time for you to hear it.
Declare them somewhere else where their lifetime is longer.

Hello, thanks for the answer.

When calling sound.play(), isn't a new thread aumatically created to play that sound and when it ends the thread dies?

What approach could I use to play a sound whenever the player clicks left mouse button? I don't know, I might be missing something still...
Title: Re: No compile errors, yet no sound.
Post by: G. on November 29, 2018, 08:22:45 pm
Yes, it plays in a thread, which is why play() is non-blocking. (= the program continues to run while the sound plays) But that thread dies when the Sound is destroyed.

// outside your main loop
sf::SoundBuffer w;
sf::Sound s;

//...

                if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
                {
                        if (gameState->mPlayerFireCooldown <= 0.0f)
                        {
                                // ...
                       
                                w.loadFromFile("../assets/shot.wav");
                                s.setBuffer(w);
                                s.play();
                        }
                }
You could even load your sound before the main loop, since loading can take time.