XNA Tutorials/Sound
From BluWiki
Contents |
[edit] Introduction
A brief tutorial on adding sound effects and music to your XNA game.
This tutorial was created by Chris Leach and Daniel Tate as part of the COMP 475 XNA Tutorials.
[edit] Adding Sound Effects
Lets add a sound effect.
[edit] Adding the sound file
XNA supports only the .wav file format for sound effects.
After you have prepared your sound file you will need to add the sound file to your content directory. Right click on content and put your mouse over Add then click on Existing Item. You can then select the sound file that you want to use.
[edit] Initializing the sound file
Declare a class-level SoundEffect object
public class MyGame : Microsoft.Xna.Framework.Game
{
// Audio objects
SoundEffect soundEffect;
}
After your object has been declared, you can load the sound file into the object in the LoadContent() method. Make sure you use the files asset name and not the file name itself. So if the file is called hello.wav, the asset name would be "hello".
protected override void LoadContent()
{
soundEffect = Content.Load<SoundEffect>("hello"); // hello.wav
}
[edit] Playing the sound file
Now that the sound effect is loaded you can play it whenever you want:
protected override void Update(GameTime gameTime)
{
soundEffect.Play();
}
[edit] Adding Music
To add music, simply add the music file to the content directory just like the sound effect.
Then declare it as a Song:
Song myMusic;
Load and play your music in LoadContent:
protected override void LoadContent()
{
myMusic = Content.Load<Song>("my music file");
MediaPlayer.Play(myMusic);
}






