Log in Page Discussion History Go to the site toolbox

XNA Tutorials/Sound

From BluWiki

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.


Adding Sound Effects

Lets add a sound effect.

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.

Adding sound file.png

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
}

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();
}


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);
}

Site Toolbox:

Personal tools
GNU Free Documentation License 1.2
This page was last modified on 23 March 2010, at 20:33.
Disclaimers - About BluWiki