How do I play a sound effect in Silverlight?
There are two ways to play a sounds in Silverlight. You can play the sound from a one media item at a time(usual for things like background music or videos etc.) or you can use the XNA SoundEffect class.
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:
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)
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)
With the current version of the emulator there is a known issue if you try to raise the pitch more than 0.5 or so, this can cause the pitch to change randomly.
Reader Comments