Saturday, November 26, 2011

XNA Tutorial: Adding sound

Download the following wave file for this tutorial


Adding file to Content Pipeline

We first need to add the sound file to the content pipeline.  Right click Content Pipeline project and add a new folder, name this folder Audio.  Then right click on the newly created folder and select 'Add Existing Item'.  Browse to where you have just downloaded the file and select it.

Loading the sound file

Add the following variable to the Game1 class

SoundEffect soundEffect;

In the LoadContent method, add the following line of code to add the audio file

soundEffect = Content.Load<SoundEffect>(@"Audio\CameraShutter");

We have loaded successfully the sound file in our variable and all we need to do now is play it.

Playing the sound file

The simplest way to play the file is to use the Play() method

soundEffect.Play();

If you need more control on the sound file, like looping, you can use the SoundEffectInstance class

SoundEffectInstance soundEffectInstance = soundEffect.CreateInstance();
soundEffectInstance.IsLooped = true;
soundEffectInstance.Play();

Try to put the above code in the LoadContent method just below the loading of the soundEffect variable and run the project.

Adding an MP3 or WMA file

If you try to load an mp3 in a SoundEffect object you will get the error

ContentLoadException: File contains Microsoft.Xna.Framework.Media.Song but trying to load as Microsoft.Xna.Framework.Audio.SoundEffect.


You will need to use the Song class in order to load an MP3 or WMA file and then play it using the MediaPlayer class.

Song mySong = Content.Load<Song>(@"Sound\mySong");
MediaPlayer.Play(mySong);
MediaPlayer.IsRepeating = true;//if you want the song to repeat

Looking for sound files for your game?

Try FreeSound.org. There are a bunch of sound effects you can choose from and most are licensed under the Creative Commons 0 License. Obviously you should still give credit to the person who created the sound file, I'm sure that everyone appreciates that ;)

If that's not enough for you why not try the following product? There are 8000+ sound files included in this package







That's it! Have fun experimenting with audio in your XNA game :)  Remember that good audio is just as important as your game visuals.