1
Audio / Re: Sound doesn't play if it was loaded and then copied in another object
« on: February 03, 2022, 11:03:54 am »SFML objects like sounds and textures are iffy to copy around, due to their attachments to other objects.
In your code:Player player;There are two Player objects. I'll refer to them as 1 and 2 to simplify it.
player = Player(3);
We have player, then we have a temporary made by Player(3). The temp is copied over the top of player.
Sounds are attached to SoundBuffers. The SoundBuffer keeps a list of every Sound that is using it (sharing soundbuffers is good for memory, many sounds to one sound buffer, like many sprites to one texture).
The temp Player is created. It's constructor loads an audio file into buf and attaches sound to buf.
Then when the temp Player is copied over player, the temp buf and sound are copied to the blank player's buf and sound.
So here's where things get tricky.
When a SoundBuffer is copied, it doesn't copy attachments.
When a Sound is copied, it attaches to the same buffer as the original was attached to.
At this point player.buf is set up, but the setBuffer's effect wasn't copied over, just the sample data. The player.sound is attached to the temporary buf, not player.buf!
After the copy, the temporary player is destructed. When a SoundBuffer is destructed, it detaches all Sounds. So player.sound is detached from the temporary buffer.
In the end player.buf is there, but has no sounds, and player.sound is there, but isn't attached to anything.
If you add this to your player class:Player& operator=(const Player& p)That should make it reattach the sound and the buffer when you do player = Player(3);
{
buf = p.buf;
sound = p.sound;
sound.setBuffer(buf);
return *this;
}
Although a better way would be to have buffers stored in a sound manager so they can be easily reused. Copying sounds around should be safe, but SoundBuffer is a resource that should only exist once for each audio file, so it's a bit trickier to deal with.
I see, I wanted to make a sound manager but I would have ran in to the same issue of having to declare an empty object in the header and then either copying into it or initializing it with another function, I tried doing this for testing and got frustrated that nothing works.
This seems logical at this point, I will try to wrap all the sound logic in a sound manager and see how this goes, thank you for the reply and help.