From the “bing” of a coin box in Super Mario Bros to the reveal chimes of the Zelda series, sound effects provide a powerful mechanism for informing the player of what is happening in your game world.
MonoGame represents sound effects with the
class. Like other asset types, we don’t normally construct this directly, we rather load it through the content pipeline. Usually, a sound effect will start as a .wav file, though a handful of other file formats are acceptable.
Once loaded, the
SoundEffect can be played with the
SoundEffect.Play() method. This is essentially a fire-and-forget method - you invoke, it and the framework takes care of loading and playing the sound.
You can also use the
SoundEffect.Play(float volume, float pitch, float pan) to customize the playback:
volumeranges from $ 0.0 $ (silence) to $ 1.0 $ (full volume)
pitchadjusts the pitch from $ -1.0 $ (down an octave) to $ 1.0 $ (up an octave), with $ 0.0 $ indicating no change
panpans the sound in stereo, with $ -1.0 $ entirely on the left speaker, and $ 1.0 $ on the right, and $ 0.0 $ centered.
Note that the per-sound-effect volume is multiplied by the static
SoundEffect.MasterVolume property. This allows for the adjustment of all sound effects in the game, separate from music.
Note that if you invoke
Play() on a sound effect multiple frames in a row, it will start playing another copy of the sound effect on each frame. The result will be an ugly mash of sound. So be sure that you only invoke
Play() once per each time you want to use the sound!
If you need finer control of your sound effects, you can also create a
from one with:
SoundEffect.CreateInstance(). This represents a single instance of a sound effect, so invoking its
Play() method will restart the sound from the beginning (essentially,
SoundEffect.Play() creates a
SoundEffectInstance that plays and disposes of itself automatically).
SoundEffectInstance exposes properties that can be used to modify its behavior:
IsLoopedis a boolean that when set to true, causes the sound effect to loop indefinitely.
Panpans the sound in stereo, with $ -1.0 $ entirely on the left speaker, and $ 1.0 $ on the right, and $ 0.0 $ centered.
Pitchadjusts the pitch from $ -1.0 $ (down an octave) to $ 1.0 $ (up an octave), with $ 0.0 $ indicating no change
Volumeranges from $ 0.0 $ (silence) to $ 1.0 $ (full volume)
SoundStateenumeration value, one of (
SoundEffectInstance also provides a number of methods:
Play()plays or resumes the sound effect
Pause()pauses the sound effect
Resume()resumes a paused sound effect
Stop()immediately stops the sound effect (so when started it starts from the beginning)
Stop(bool immediate)also stops the sound effect, immediately if
true, or its authored release phase, i.e. a fade, if
Perhaps the strongest reason for creating a
SoundEffectInstance is to be able to crate positional sound. We’ll discuss this next.