SFML community forums

Help => Audio => Topic started by: Moonglum on May 16, 2023, 10:57:09 am

Title: unable to hear sound
Post by: Moonglum on May 16, 2023, 10:57:09 am
Hi All.  Trying to play sound. Seems to load the file ok but cannot hear playback. App is not muted and I can hear the playback from Windows directly. I have included the Audio.hpp and it can find the flac file. I tried .wav file but again, no sound. Everything else from SFML works ok. Source code is ...

    sf::SoundBuffer shootBuffer;
    if (!shootBuffer.loadFromFile("shoot.flac"))
    {
        return -1;
    }
    else
    {
        sf::Sound shoot;
        shoot.setBuffer(shootBuffer);
        shoot.play();
    }

Any clues? Much appreciated as always.

Moon.
Title: Re: unable to hear sound
Post by: eXpl0it3r on May 16, 2023, 01:46:35 pm
The sf::Sound instance needs to be kept alive for as long as you're playing the sound.

In your example code the sf::Sound instance is destroyed when the else body scope is closed, so right after calling play, thus nothing is being played.
Title: Re: unable to hear sound
Post by: Moonglum on May 16, 2023, 04:43:00 pm
Oh wow! Thanks for coming back to me. Yes that worked. Removed the 'Else' and I can here the sound now, but only for that one play.  Do you really have to load the file in to the buffer every time you want to play the sound?  Does seem excessive, but thanks anyway.

Moon.
Title: Re: unable to hear sound
Post by: eXpl0it3r on May 16, 2023, 07:57:31 pm
You don't have to reload the buffer every time.
I recommend having a look at the sound tutorial: https://www.sfml-dev.org/tutorials/latest/audio-sounds.php

You need to keep the sf::SoundBuffer instance alive for as long as you want to use that sound.
And you need to keep the sf::Sound instance alive for as long as the sound is playing.
If you want to repeat the same sound, you can also set the sound to looping.