SFML community forums

Help => Audio => Topic started by: PepperedJerky on March 03, 2022, 08:27:18 am

Title: Sounds in deque not playing
Post by: PepperedJerky on March 03, 2022, 08:27:18 am
So basically I have a Sound deque and an audio buffer in the global scope, and the audio buffer is initialized from a wav file in the main fn. I have a function called "physicsUpdate" which is called every 10 ms, and in this function there is an if check to see if a ball has collided with a wall. When a ball collides, I emplace_back a sound and pass the audio buffer, then initialize some properties of the sound and call play. But it does not play. Here is the code only including the parts I mentioned above and a few related parts:

using namespace sf;

SoundBuffer audioBuff;
std::deque<Sound> sounds;

Clock physicsUpdateInterval;

void physicsUpdate();

int main() {
    if(!audioBuff.loadFromFile("ball.wav")) return 1;

    Listener::setGlobalVolume(100.f);
    Listener::setPosition(windowSize.x/2, 0.f, windowSize.y/2);

    while (window.isOpen()) {
        if(physicsUpdateInterval.getElapsedTime().asMilliseconds() >= 10) physicsUpdate();
    }

    return 0;
}

void physicsUpdate() {
    physicsUpdateInterval.restart();

    for(uint16_t i = 0; i < ballCount; i++) {

        if((xWallsCollide && !ball.xColliding) || (yWallsCollide && !ball.yColliding)) {
            std::cout << "Sound create!" << std::endl;
            sounds.emplace_back(audioBuff);
            Sound sound = sounds.back();

            sound.setPosition(ball.pos.x, 0.f, ball.pos.y);
            sound.setMinDistance(600.f);
            sound.setAttenuation(5.f);
            sound.play();
        }
    }
}
 

Any ideas what is wrong here? Thanks :)
Title: Re: Sounds in deque not playing
Post by: eXpl0it3r on March 03, 2022, 09:43:20 am
You copy the back() entry out of the deque and its life-time is limited by the function scope.
So at the end of physicsUpdate() the copy of the Sound object is destroyed and the sound stops playing.

Additionally, you shouldn't be using globals.
It's much better to create a wrapper class and have things as member function and member variables.
Title: Re: Sounds in deque not playing
Post by: PepperedJerky on March 03, 2022, 04:11:11 pm
Ah okay thank you, a simple & fixed it haha.