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

Author Topic: setBuffer Issue  (Read 2574 times)

0 Members and 1 Guest are viewing this topic.

waleed mujeeb

  • Newbie
  • *
  • Posts: 4
    • View Profile
setBuffer Issue
« 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.

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6287
  • Thor Developer
    • View Profile
    • Bromeon
Re: setBuffer Issue
« Reply #1 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().
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development:

waleed mujeeb

  • Newbie
  • *
  • Posts: 4
    • View Profile
Re: setBuffer Issue
« Reply #2 on: April 04, 2013, 10:16:48 pm »
Thanks. reserve function worked.