SFML community forums

Help => Audio => Topic started by: Teknol on September 18, 2017, 02:38:34 am

Title: Making sound replay after it finishes playing
Post by: Teknol on September 18, 2017, 02:38:34 am
So I'm making a jetpack joyride game and I wanted to add some sound.
Currently it plays the sound while you are flying but it replays the sound every frame and it sounds really annoying.

How can I make it replay a sound only after it finishes playing that sound. I will also want it to instantly stop the sound as soon as I release the space bar.

Thank you!


Sent from my iPhone using Tapatalk
Title: Re: Making sound replay after it finishes playing
Post by: Hapax on September 18, 2017, 03:53:26 am
Enable the sound's loop (https://www.sfml-dev.org/documentation/2.4.2/classsf_1_1Sound.php#af23ab4f78f975bbabac031102321612b) and then play the sound once when the key is first pressed. It will loop continuously until you stop it. You can then stop it (again, once) when the key is released.

Vague idea:
sound.setLoop(true);
// window loop
    if (spaceBarWasJustPressed)
        sound.play();
    else if (spaceBarWasJustReleased)
        sound.stop();

Since you (now) want to do something whenever a key state is changed, it's easier to use events (sf::Event::KeyPressed and sf::Event::KeyReleased (https://www.sfml-dev.org/tutorials/2.4/window-events.php#the-keypressed-and-keyreleased-events))
Title: Making sound replay after it finishes playing
Post by: Teknol on September 19, 2017, 01:03:17 am
Thanks a lot! With a little bit of adjusting I was able to make my sound slowly fade. I adjusted the speed of it fading so that I can spam without the sound coming too late

I used 3 Booleans and (probably I could manage to use only two, I'll try). If space is pressed a Boolean returns true, it plays music, sets another Boolean to false, then sets itself to false. Once space is released it stops the music and makes that other Boolean true. The music space_pressed Boolean can only return true while the other Boolean is also true, preventing it self switching on then off and again and again.


Sent from my iPhone using Tapatalk