Table of Contents

How to loop Sounds

This section demonstrates how to loop a sound.

Overview

In this example we will go over the basics of how to make sound effects loop rather than the default play once.

Simple Sound Looping

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.

To loop a sound

  1. Follow the instructions show in Playing a Sound topic.

  2. Declare a SoundEffectInstance object to hold an instance of the sound file.

    private SoundEffectInstance soundEffectInstance;
    
  3. 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();
    
  4. 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;
    
  5. 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.

See Also

Reference

© 2012 Microsoft Corporation. All rights reserved.