Listing 5-6
float volume = 1.0f;
AudioCategory category;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
content = new ContentManager(Services);
audio = new AudioEngine("Chapter5sounds.xgs");
wavebank = new WaveBank(audio, "Wave Bank.xwb");
soundbank = new SoundBank(audio, "Sound Bank.xsb");
category = audio.GetCategory("Default");
}
The Default category is what every sound is set to that you add to
an XACT project. You can create your own categories and group the
sounds as you’d like. The one caveat here is that all the sounds in a
group are affected by the change in volume, so you’ll need to plan
accordingly if you’re going to make volumes dynamic in your game.
Playing 3D Sound
Playing 3D sounds is just a bit more difficult than playing 2D
sounds. There are a couple of extra objects that you’ll need to
create and some calculations to do. There’s a lot of power in XACT
for doing 3D sounds and you can go as deep as you want or need to.
For our purposes, we’ll just need the basics.
Let’s add the necessary objects for doing basic 3D sound to the
project:
Listing 5-7
AudioEmitter emitter;
AudioListener listener;
Vector3 position;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
content = new ContentManager(Services);
198 Chapter 5
audio = new AudioEngine("Chapter5sounds.xgs");
wavebank = new WaveBank(audio, "Wave Bank.xwb");
soundbank = new SoundBank(audio, "Sound Bank.xsb");
category = audio.GetCategory("Default");
emitter = new AudioEmitter();
listener = new AudioListener();
}
The AudioEmitter object is used to set the position from where the
sound emanates. The AudioListener is used to set the position of
the object that is listening to the sound. In a 2D game, these will
usually not be set to anything, although there’s no reason why you
couldn’t change the position of the listener. In a 3D game, either
object or both could be moving and the sound would be played
accordingly.
We need to add just a couple of lines of code in the Update
method to get some 3D sound:
Listing 5-8
position = new Vector3(_curState.ThumbSticks.Left.X, 0.0f,
_curState.ThumbSticks.Left.Y);
emitter.Position = position;
if (_curState.Buttons.A == ButtonState.Pressed)
{
if (!titleCue.IsPlaying)
{
titleCue = soundbank.GetCue("title");
titleCue.Play();
}
else if (titleCue.IsPaused)
titleCue.Resume();
else if (titleCue.IsPlaying)
titleCue.Pause();
}
If you hold down the A button and move the left thumbstick around
in a circle, you’ll hear the sound moving around you. As you move it
from one side to the other, the sound fades from the direction being
moved from and increases in the direction being moved to.
Sound 199

Get Essential XNA Game Studio 2.0 Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.