# 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.Volume = fade * fade * baseVolume;
sound.Pan = MathHelper.Clamp(screenDistance.X, -1, 1);
return fade > 0;
}


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.

Of course, for a 2D game, how quickly you pan and how quickly you fade out sounds as they go off screen will depend on your game. You should modify the maths to suit your own game's mood.

• This is the easiest way to go if you're looking for just basic positioning. But if you want doppler, you're probably better off with the tutorial that The Communist Duck posted. Also, being able to setup 3d properties in the XACT authoring tool makes it really convenient to use. – michael.bartnett Mar 15 '11 at 4:42
• 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
• I didn't realize there wasn't any XACT support for Windows Phone, that's a serious buzzkill. Good to have this bit of code around then, thanks for the followup! – michael.bartnett Mar 15 '11 at 23:15

There is a 3D audio example on XNA's app hub. I'm pretty sure you can take the same concept for 2D.