title | description | requireMSLicense |
---|---|---|
How to loop Sounds |
This section demonstrates how to loop a sound. |
true |
In this example we will go over the basics of how to make sound effects loop rather than the default play once.
Not much extra code is needed to continuously loop a sound file in your game. Since the SoundEffect class does not provide looping support, you will need to allocate a SoundEffectInstance object. The following procedure builds on the sample code provided in the Playing a Sound topic.
-
Follow the instructions show in Playing a Sound topic.
-
Declare a SoundEffectInstance object to hold an instance of the sound file.
private SoundEffectInstance soundEffectInstance;
-
To be able to loop a sound you will need to declare a SoundEffectInstance object, and set it to the return value of SoundEffect.CreateInstance. add this after loading the sound file in the
LoadContent
method.soundEffectInstance = soundEffect.CreateInstance();
-
Set SoundEffectInstance.IsLooped to true which will cause the sound effect to play forever or until you stop it or close the game.
soundEffectInstance.IsLooped = true;
-
Play the sound instance (removing the old soundEffect.Play() call).
// Play the sound effect instance soundEffectInstance.Play();
Note
Obviously you would not normally call play
in the LoadContent
method, we just use here as an example.
-
Demonstrates how to play a simple sound by using SoundEffect.
-
SoundEffect Class
Provides a loaded sound resource.
-
SoundEffectInstance Class
Provides a single playing, paused, or stopped instance of a SoundEffect sound.