Wednesday, October 15, 2008

XNA Part 7 - Audio - Sound Effects

In our last installment, we talked a little about the Song object and how to load a music file and play it in our games. In this post we will talk about the SoundEffect Object. From my understanding the difference between these two types is in a. how they are stored and b. how they are played. Sound effects are considered shorter burts of sound that will be played from beginning to end rather than started, paused, stopped, etc. If there is a XNA genius here who wants to add to the finer details of this, please do so in the comments.

So to add a sound effect to our project, we will add it the same way in our content pipeline. We will add a folder under content called sounds and then add our sound file to that folder.

The difference comes in how we access that file. Rather than exposing that sound file with a Song object, we will load it into a SoundEffect object. So at the top of our class we will add a variable of type SoundEffect called fx.

SoundEffect fx;

Then in our LoadContent method, we will call
fx = Content.Load("sounds\\effect");

Now since this sound effect should be triggered by something happening in our game, we want to play it during our update method.

I am going to add it to the block of code that gets executed when we press the spacebar.

if (ks.IsKeyDown(Keys.Space)) { fx.Play(); }

As you can see we do not use the MediaPlayer class to play a SoundEffect file. They have a built in method to play themselves. Now the Play has 3 versions. the first takes no parameters and just plays the sound at the full volume. The second takes a float for volume control (between 0 and 1) and the 3rd takes a float for volume, a float between -1 and 1 for pitch to move the sound down or up an octave, a float for panning (between -1 left and 1 right, 0 center) and a bool to indicate if the sound should just keep looping.

If we just call fx.Play() it is sort of a set it and forget it sort of deal. It plays, ends and that is it. But if you need additional control over the sound effect after it is started, then you need to save the return value of fx.Play() which is an instance of type SoundEffectInstance. So you would do this.

SoundEffectInstance e = fx.Play(.1f, 0.0f, 0.0f, true);

now the variable e can be used to control this instance of the playing sound effect. It has methods such as Stop, Play, Resume and variables like volume, pan, pitch, islooped, and state (which tells us what the sound is currently doing). That way if you created a SoundEffect as looping, you could stop it with e.Stop();

So now as we move along, you can very easily add sound effects to your games and make them a lot more interesting.

One note, as you progress into 3d games, there are ways to place a sound within 3d space and the SoundEffect objects have methods for dealing with this as well.
Post a Comment