Game Development Reference
In-Depth Information
The order in which these methods are called is very important! Because we want the
balloon to appear on top of the background, we first have to draw the background,
then we draw the balloon. If we did this the other way around, the background would
be drawn over the balloon, and we would not see it anymore (try it yourself).
4.3.6 Music and Sounds
Another type of commonly used game asset is sound . Generally, we distinguish
between two types of sound in games: background music, and sound effects. Sound
effects are very useful to indicate to the player that something is done, or something
has happened, for example when the player picks up a new weapon or when a level
is completed. In XNA, it is very easy to play background music and sound effects.
In order to use sound, we first need a sound file that we can play. In the SpriteDrawing
program, we are going to play the file 'snd_music' which will serve as background
music. As you can see, this file is located inside the content project. If you right
click on this file and you select the properties, you can see that there is a field
called 'content processor'. This indicates what kind of content we are dealing with.
Select 'Song' as the content processor type. By doing this we can use the music file
as background music. For sound effects, there is another related content processor
type which (surprise!) is called 'Sound Effect'.
In order to play background music in our program, we need access to the Media
library. This means that we have to add a using -instruction:
using Microsoft.Xna.Framework.Media;
In the LoadContent method, we can then load the sound file, and play it as background
music:
MediaPlayer.Play(Content.Load<Song>("snd_music"));
We call the method Play from the MediaPlayer class, and we pass as a parameter
the Song object that was loaded. As you can see, adding background music to your
game is easy: it only requires a few lines of code. Playing a sound effect is also
very easy. Sound effects are part of the Audio library, so we need the following
using -instruction:
using Microsoft.Xna.Framework.Audio;
Loading the sound effect is done as follows:
SoundEffect mySound = Content.Load<SoundEffect>("scream");
And we play the sound effect by calling the Play method on the object:
Search WWH ::




Custom Search