SoundEffects in Windows Phone Silverlight

Buildings

Silverlight in Windows Phone is a great place to write games. I’m having to pick up a whole bunch of new skills but I reckon that it is well worth the effort. One piece of effort that I’ve had to put in is on playing sounds. It turns out that you use the SoundEffect class from XNA to get the sounds out of your games.

The first step is to add the XNA libraries to your game. Open up the References tab in your project and add the Microsoft.XNA.Framework reference.

Now add a couple of using statements to your program to make the XNA classes easier to get hold of:

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;

The sound you want to play has to be added to your project. You don’t use the Content Manager in Silverlight though, as there isn’t one.  Instead you add the item as content. Make sure that the build action for the resource is set to Content. As with old school XNA, a SoundEffect can be wav file. I just dropped a beep file into the root level:

image

You can also see here that I’ve loaded the framework. Now I can load the SoundEffect in my game:

SoundEffect beep =
             SoundEffect.FromStream(TitleContainer.OpenStream("beep.wav"));

The static FromSteam method will fetch the effect from a stream. The TitleContainer object fills in for the Content Manager in XNA. If you want to put your sounds into a folder you can, but you must give the path (separated using the / character)

image

Sounds folder as part of the project

SoundEffect beep =
   
SoundEffect.FromStream(TitleContainer.OpenStream("Sounds/beep.wav"));

Now I can play my beep sound in the usual way:

beep.Play();

This is the boring form of the Play method call. You can also control the volume, pitch and left-right panning of the sound as well:

beep.Play(
    0.5f,   // half volume
    1.00f,   // one octave higher (-1 is 1 octave lower)
    -1.0f); // on the left (+1 is the right)

Actually, I’ve noticed what might be a problem here. The documentation says that the pitch value goes from –1 (one octave lower) to 1 (one octave higher). This used to work fine when I used XNA 3.1.  When I go for pitches greater than 0.6 I get really weird sounds. I’m not sure why this is, but I’m trying to find out.