monogame

Playing Sounds

Sounds using SoundEffect

In order to play a sound using the SoundEffect type, create a variable to hold the loaded sound. Typically this would be an instance variable in the Game class:

private SoundEffect mySound;

Then, in the LoadContent() method of the Game class:

protected override void LoadContent()
{
    // load the audio content
    mySound = Content.Load("mySound");
}

Finally, whenever the sound needs to be played, just invoke the Play() method:

bool played = mySound.Play();

If for some reason, such as too many sounds are already playing, the Play() method may return false. If the sound started playing successfully, then it will return true.

Controlling the playback using SoundEffectInstance

SoundEffect.Play() plays the sound effect in a “fire-and-forget” fashion. The sound plays once and its lifetime is managed by the framework. You are not able to change the properties (volume, pan, pitch) of the sound during playback, loop it, position it in 3D or pause it.

You can hold a reference to the playing sound by creating a SoundEffectInstance. Instead of calling SoundEffect.Play(), call CreateInstance() on the SoundEffect and then Play() on the new instance:

SoundEffectInstance instance = mySound.CreateInstance();

// Set some properties
instance.Pitch = 1.0f;
instance.IsLooped = true;

// Play the sound effect
instance.Play();

There can be multiple instances of the same SoundEffect, each with their own properties. The instance can be replayed by calling Play() after the playback has stopped.


This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow