Matthias Shapiro

I need fewer hobbies

Embedding a Sound File in Windows Phone 7 app (Silverlight)

Normally, I wouldn’t blog something that seems obvious, but it took me hours to figure this out and I always try to write blog posts for stuff that it took me a long time to figure out. Enormous props to Walt Ritscher (Twitter: @waltritscher) who helped me figure this out.

This blog post is for you if you have a sound file and you want it to:

  1. be included with the application when the user downloads the app
  2. play no matter what… even if the user is listening to music

First, grab the audio you want to add to the application and, if it’s not already a .wav file, make it so. If you’re just trying this out for kicks (or for the learning experience), download this files.

Coyote.wav

When prepping your audio, keep in mind if you want the user to hear it over their music. If so, make sure it is LOUD. I spent almost an hour thinking this method didn’t work because I couldn’t hear the sound over my music.

Next, create a directory in your Windows Phone 7 project and add your audio file like so:

image

Then select your audio file and change the “Build Action” to “Resource”

image

Now right-click on the “References” in your project and click “Add Reference…”. Find the “Microsoft.Xna.Framework” reference and add it to your project.

image

image

To the top of your class, add:

using Microsoft.Xna.Framework;

Now we’re going to create a stream from that resource and use that stream to play our sound.

StreamResourceInfo streamInfo = Application.GetResourceStream(
new Uri("/MyProjectName;component/Sound/Coyote.wav",
UriKind.Relative));
SoundEffect se = SoundEffect.FromStream(streamInfo.Stream);
SoundEffectInstance soundInstance = se.CreateInstance();
soundInstance.Play();

And that’s it. Your sound should play.

If you’re reading this, I assume you’re working with sound in some capacity. If you’re new to the work of sound and just want a simple way to edit and export sound files for your app, I highly recommend the free sound editing application Audacity. It saved me on my current project.

If you’re using Audacity and editing/creating sounds to hear while music is running, take whatever sound you have and amp up the gain so that the volume is peaking at about 0.

image

This sounds extreme, but it’s the only way I’ve been able to get the sounds to reliably make themselves heard over rock music.

I also recommend checking out Jaime Rodriguez’s post on running a Windows Phone app under the lock screen. That way you can play sounds even if the user allows the phone to lock itself.

0 Responses to Embedding a Sound File in Windows Phone 7 app (Silverlight)

  1. Surbhi Agarwal

    Outstanding!! really very good explanation. I searched first time to embed an audio in my wp7 app and got the best:) really a good job