Tuesday, October 14, 2008

XNA Part 6 - Audio - Music

Today we will take a slight detour from our drawing of textures to another very important part of games. The audio! Music and sound effects are incredibly important parts of games no matter if you are doing a simple pong game to a massively multiplayer online game.

There are 2 basic type of audio that I want to talk about today. Music and Sound Effects. Now please remember what I am going to talk about today is part of XNA Game Studio 3 beta using Visual C# 2008, not XNA Game Studio 2.

Lets start with music. First, just like with textures, we want to add our music to the content pipeline. Depending on how much music and sound you are adding to your project, you may want to create 2 folders under content. One for Music and one for Sound Effects. So right click on content in the solution explorer and add a new folder and call it music. Then right click on the music folder and 'add'->'existing item' change the type to audio files (you will see that you can load xap,wav,wma and mp3 files) and browse to your music file and add it.

In our code, we will add an instance variable to our Game class to hold a reference to a song object. so somewhere after

public class Game1 : Microsoft.Xna.Framework.Game {


Song mySong;

and in the LoadContent method, add the line

mySong = Content.Load("music\\musictrack");

where musictrack is the name of your music file. if you want it to start playing immediately, one the next line put


and that is it, your song will begin playing at the beginning of the program.

Now your mySong object also exposes some info about your song like
Name,Album, Artist, Duration, Genre, etc if they are available, and the MediaPlayer class has several static methods for Playing, Pausing, Changing Volume, Queuing songs, etc. You can set the volume with

MediaPlayer.Volume = 1.0f;

Or in your update call check for certain keys like we did with movement and change the volume based on key presses.

So next time we will look at the equally easy way to cue up sound effects for your game.
Post a Comment