home

Tutorial Index

XNA Tutorial 4: Playing a sound effect

Sound is also very straightforward in XNA, so much that no intro is actually required!
Import the sound into the project just like you did with textures. WAV is the preferred format in most environments, however MP3 should be fine too.

Other than the project knowing of the existence of the sound, the program must store it too, so you will create a SoundEffect object with a suitable name, let’s assume it to be mySoundEffect. The same content.Load<>() function is used, I trust it is now more obvious to understand how the <> symbols work. In this case, similarly assuming that content is the default ContentManager, the command should be

mySoundEffect = content.Load<SoundEffect>(“my_effect”);

Now, to get this to play, you will use a function that is built into the class, conveniently,

mySoundEffect.Play();

and that’s it. This will play the sound effect once and then stop. Note that though you can overlap sounds without any problems, if you repeatedly play the same effect at a high rate, the sound will be distorted beyond all recognition, it might remind you of the sound exploding cars mage in GTA: Vice City to some extent, that metallic vibrating sound.  Try to limit the rate at which the effect is being played using timers (next tutorial).

Now, to go more into depth, we shall see how you loop the sound. This is useful if you want music to play in the background for example, though it is most commonly used for engines of vehicles. To do that you create an object called SoundEffectInstance, assigning it the returned object from mySoundEffect.CreateInstance(). After that, all you need to do is call it’s Play() function.

This class has many interesting functions that I suggest you check out on MSDN. Other than Pause(), Stop() and Resume(), an additional function is Apply3D(), which gives it a position in 3D space, taking as arguments one or more listeners and an emitter. This will probably not be of use to you currently, but if you move into 3D XNA programming, it will be of great value.

Note that you may have up to 16 different SoundEffectInstance object playing simultaneously, this should be more than enough however.

Now you can add some life to your game, essentially anything that does not require rotation of images can now be done with what you know.

In the next tutorial we will talk about timing, which opens many more opportunities, from well balanced animation to timed events, this will essentially complete the needed knowledge in terms of the language you need to know to develop your projects. After this, in the 2D realm, you will probably only need rotation commands.

Future tutorials will mostly focus on how things are done effectively, from collision detection to better animation in terms of code, for example how to make particle effects or effect changes in the state of actors.

‘Till next time, happy coding!