Sound emmiters with panning and volume in 2D

How can I create sound emmiters that pan and change volume based on distance from the player in a 2D game?

• Just an FYI, most 3D sound APIs automagically map from surround to stereo sound output, chances are you do not have to do anything special beyond what you would normally do :) – James Mar 14 '11 at 22:55

Use SoundEffect.CreateInstance(); to get a SoundEffectInstance of your chosen sound effect.

You can then Play() that instance while modifying its Volume and Pan properties.

Or, if it's a short, one-shot sound effect, you can simply use SoundEffect.Play(volume, pitch, pan); to play it at your chosen volume and panning.

Here is some code that I have used in the past to set the volume and panning of a SoundEffectInstance based on the emitting object's position and the camera:

public bool SetSoundForCamera(SoundEffectInstance sound, Vector2 position, float baseVolume)
{
Vector2 screenDistance = (position-cameraCenter) / cameraHalfSize;
float fade = MathHelper.Clamp(2f - screenDistance.Length(), 0, 1);
sound.Pan = MathHelper.Clamp(screenDistance.X, -1, 1);

For a SoundEffectInstance, simply call that each frame while the sound is playing. You could extract the maths and use it for one-shot sounds as well.
• The downside to XACT (Cue instead of SoundEffectInstance) is that it doesn't work on Windows Phone. Of course, using SoundEffectInstance.Apply3D instead of my SetSoundForCamera is fine too. – Andrew Russell Mar 15 '11 at 8:08