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

Author Topic: Sounds in deque not playing  (Read 2729 times)

0 Members and 1 Guest are viewing this topic.

PepperedJerky

  • Newbie
  • *
  • Posts: 2
    • View Profile
Sounds in deque not playing
« 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 :)

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 10801
    • View Profile
    • development blog
    • Email
Re: Sounds in deque not playing
« Reply #1 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.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

PepperedJerky

  • Newbie
  • *
  • Posts: 2
    • View Profile
Re: Sounds in deque not playing
« Reply #2 on: March 03, 2022, 04:11:11 pm »
Ah okay thank you, a simple & fixed it haha.

 

anything