Windows Phone 7: Playing Sound Effects


I was recently wanting to play a “pop” sound on a user control that looked like a bubble when it was burst. In my first attempt, I used the MediaElement with the following code (and it lagged terribly):

<MediaElement x:name="PopSoundMediaElement" />
PopSoundMediaElement.AutoPlay = False
PopSoundMediaElement.Source = New Uri("Resources/Pop1.mp3", UriKind.Relative)

I made sure that I wasn’t reading the stream in multiple times (e.g. a performance problem caused by multiple loadings). Nothing I tried seemed to help the lag. After reading up a bit I added references to the “Microsoft.Xna.Framework” library and decided to use the SoundEffect class.

You will want to put imports to Microsoft.Xna.Framework.Audio and Microsoft.Xna.Framework in your code (using with C#).

Imports Microsoft.Xna.Framework.Audio
Imports Microsoft.Xna.Framework

Next, in my user control I created a class wide variable for the SoundEffect (I don’t know how the streams are handled here, it’s possible I may want to create the stream outside of the control and reference it in multiple controls, I haven’t tested performance though).

Private _sf As SoundEffect

In the “Loaded” event of my control, I added the following code to setup the SoundEffect (I should note, stream is declared implicitly here much like a var declaration in C#). The .wav file here is set with a Build Action of “Content” and a “Copy if Newer” property (you can set those properties via the Solution Explorer in Visual Studio).

FrameworkDispatcher.Update()
Dim stream = TitleContainer.OpenStream("Resources/Pop1.wav")
_sf = SoundEffect.FromStream(stream)

When I want to play the pop sound now, I can use this line of code:

_sf.Play()

So far, this method doesn’t seem to lag my app at all. I’ve initially tested it in both the Emulator and on an HTC Trophy. I haven’t tested however how much better performance would be if the controls shared a stream (or researched if the TitleContainer somehow handles that for you). At this point, all I know is the above Xna calls work WAY faster than the MediaElement.