Game Development Reference
In-Depth Information
Similar to
sf::Texture
, sound buffers have methods to load from memory
(
SoundBuffer::loadFromMemory()
) and to load from a stream
(
SoundBuffer::loadFromStream()
). A texture can also be loaded from an array
of pixels but, in terms of sound buffers, this doesn't really make sense. Instead, the
SoundBuffer
class has a method of loading from an array of samples
(
SoundBuffer::loadFromSamples()
).
As soon as we create
sf::Sound
by calling its constructor and passing the sound buffer,
we can play it with
Sound::play()
. The method does different things, depending on
the current status of
Sound
. The method plays the sound in another thread, so the current
thread isn't blocked.
Every
SoundSource
object has
SoundSource::Status
(enum) associated with it.
It can be one of three states:
Stopped
,
Paused
, or
Playing
. This state system is used in-
ternally in the
SoundSource
class to control the behavior of its methods. It is possible
to get the status of a
Sound
or
Music
object by calling their
getState()
methods.
Going back to
Sound::play()
, in a state of stopped or paused, the method starts play-
ing the sound from its current playing position. If it was in a playing state though, it would
restart the sound. This means that we have to be careful when we want to play the same
sound multiple times. The best solution to this is to create multiple
Sound
instances each
time the sound needs to be played. Since all of these instances use the same
SoundBuffer
instance, creating sounds is extremely quick and lightweight so we do
not have to worry about performance or memory.
The
Sound
class has methods for stopping and pausing the sound as
well—
Sound::stop()
and
Sound::pause()
, respectively. The
Sound::stop()
method stops the sound and resets the playing position to the start if it is currently in a
playing or paused state. If the sound is in a stopped state, the method does nothing. Simil-
arly,
Sound::pause()
stops the sound playback, but doesn't reset the playing position.
If the sound is in a stopped or paused state, the method does nothing.
We can set if the sound should be loopable or not, with
Sound::setLoop()
. If the
sound is set to loop, then it will restart from the beginning at the end. By default, each
sound is not loopable.