SFML community forums

Help => Audio => Topic started by: waleed mujeeb on April 04, 2013, 10:07:11 pm

Title: setBuffer Issue
Post by: waleed mujeeb on April 04, 2013, 10:07:11 pm
IDE: CodeBlocks 10.05
Compiler: GCC 4.6.2
OS: WinXp 32bit
Language: C++
API: SFML-2.0-rc-win32-mingW-dw2
Linking: Static with sfml debug libs
 std::vector<sf::SoundBuffer> sound_buffer;
 std::vector<sf::Sound> sound;
int i=0;
 while(!file.eof())
    {
       file>>state;
        file>>file_name;
         sound_buffer.push_back(sf::SoundBuffer());
         sound_buffer[i].loadFromFile(dir+file_name)
       sound.push_back(sf::Sound());
      sound[i].setBuffer(sound_buffer[i]);
       ++i;
    }
 
Problem: I am making a small game. file has state name with associated sound_file.
eg. DIE death.wav
     SHOOT shoot.wav

For some reason,except for some, most of the elements in sound vector are set to NULL. So they dont play.
If i change above code to this, it starts to work without any problem

while(!file.eof())
    {
       file>>state;
        file>>file_name;
         sound_buffer.push_back(sf::SoundBuffer());
         sound_buffer[i].loadFromFile(dir+file_name)
         ++i;
    }

for(int i=0; i!=sound_buffer.size(); ++i)
{
        sound.push_back(sf::Sound());
      sound[i].setBuffer(sound_buffer[i]);
}
 
I cant seem to figure out why it doesnt work in the first code. I could use a hint.
Title: Re: setBuffer Issue
Post by: Nexus on April 04, 2013, 10:10:03 pm
std::vector reallocates memory as it increases, and copies elements to another location. As a result, pointers to the sound buffers become invalid.

There are different solutions. You could take a stable STL container like std::list, or pre-allocate memory with std::vector::reserve().
Title: Re: setBuffer Issue
Post by: waleed mujeeb on April 04, 2013, 10:16:48 pm
Thanks. reserve function worked.