Game Development Reference
In-Depth Information
Sound versus music
At first glance, the existence of these two classes might seem odd, but they ultimately serve
different purposes, and it's all due to how they are implemented.
The
Sound
class loads all of its data into system memory, and this makes playing the au-
dio sample very quick. The
Music
class, on the other hand, opens a stream to a file on the
hard drive (or the RAM) and loads small chunks of data, which are played one after the
other. Due to its design, the
Music
class has a playback delay due to transferring the data
at such a slow place.
Both the classes provide different benefits—the
Sound
class almost instantly plays, but
takes a lot of system memory, whereas the
Music
class is slower to play, but doesn't use
much RAM at all. As such, both the classes are useful in different situations. For example,
if the audio file is small enough to store in system memory, we should load it using the
Sound
class. This is applicable when the sound is to be played instantaneously after we
call its
play()
method. Sometimes, we have to make memory sacrifices when the file is
too big, and it has to be played immediately—that's why resource management is important
(to remove unused assets and load new ones). The
Music
class, on the other hand, is
mostly used for big audio files, where it is not important even if their playback is delayed a
bit at the start. This class is mostly used for the background music in the game.
Sound
and
Music
have the same class in their inheritance tree,
SoundSource
, which
provides a common audio functionality, such as altering the pitch and 3D positioning.The
Sound
class derives from it directly, whereas
Music
derives from
SoundStream
. Fin-
ally
SoundStream
derives from
SoundSource
. The following diagram demonstrates
their relation:
We will find out more about
SoundSource
and
SoundStream
later in this chapter.