SFML community forums

Help => Audio => Topic started by: Perde on March 15, 2014, 05:59:43 pm

Title: [Solved] Need help identifying the problem with my sounds.
Post by: Perde on March 15, 2014, 05:59:43 pm
I'm in dire need of help once more.  ::)
I have a small class that manages my sf::SoundBuffers and also sf::Sounds.

It contains this method right here, whose task is to first search for sounds that stopped playing and possibly remove them from a vector (of structs that contain the sound itself and a std::string), and continue by playing the desired sound.
As you can see, I search a vector of sf::SoundBuffers (same structure as above) for the name of the file, create a new sound instance, add it to the vector and play it. It works perfectly fine as long as sounds from different files are played at the same time. However, if I try to play the sound from a single file/buffer more than once at the same time, the first just stops abruptly.
If I play the same sound more than two times, it's a complete mess. Sometimes it works and some of the sounds play, sometimes all get cut off.
If I remove "this->sounds.back().sound.play();", everything seems to work (the cleanup gets triggered all the time, but only as expected).
It's obvious that I'm doing something wrong, but I simply can't figure it out.

void ac::SoundStorageDebug::play(std::string file)
{
    std::vector<ac::SoundStorageDebug::Sound>::iterator i = this->sounds.begin();
    while(i != this->sounds.end())
    {
        if(i->sound.getStatus() != sf::Sound::Playing)
        {
            std::cout << i->sound.getStatus() << std::endl;
            i = this->sounds.erase(i);
            std::cout << "sound removed" << std::endl;
        }
        else
            ++i;
    }
    for(std::vector<ac::SoundStorageDebug::Buffer>::iterator i = this->buffers.begin(); i != this->buffers.end(); ++i)
    {
        if(i->file.compare(file) == 0)
        {
            ac::SoundStorageDebug::Sound tmp;
            this->sounds.push_back(tmp);
            this->sounds.back().file.assign(i->file);
            this->sounds.back().sound.setBuffer(i->buffer);
            this->sounds.back().sound.play();
            std::cout << "sound created" << std::endl;
        }
    }
}
Title: Re: Need help identifying the problem with my sounds.
Post by: Perde on March 15, 2014, 09:08:10 pm
Okay! Switching to a std::list to store the sf::Sound instances has solved the issue. I have no idea why though.  ;D
Title: Re: [Solved] Need help identifying the problem with my sounds.
Post by: eXpl0it3r on March 15, 2014, 11:29:28 pm
There are a few threads about this on the forum already. The thing is, that when you push_back a new element into a std::vector it will have to resize itself at one point, thus moving all elements somewhere else, which invalidates all pointers to the specific elements, which let the sf::Sound fail playing the audio. With a std::list you won't get that invalidation. ;)