To play sounds on the Windows Phone 7 you can make use of the SoundEffect library that comes with XNA even if you are building an application in Silverlight.
Start by adding a reference to Microsoft.Xna.Framework.dll.
Next, add the following using statements to your file:
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework;
This class supports using WAV files. If you have an MP3 file, you can convert it to a WAV using a conversion tool (there are tons of free tools on the Internet).
Next, add your wav file to your project. Finally, open the stream to the WAV file using TitleContainer.OpenStream() and create a SoundEffect from that stream. In the example below, I am opening a wave file called crickets.wav that is located in my folder called sounds.
Stream stream = TitleContainer.OpenStream("sounds/crickets.wav");
SoundEffect effect = SoundEffect.FromStream(stream);
FrameworkDispatcher.Update();
effect.Play();
In general wave files are much larger than compressed MP3 files. On the phone, you can play one Mp3 at a time using the MediaElement object. When creating your MediaElement, make certain you add it to the Silverlight tree if it’s not statically declared otherwise it will not load.
Also, when you deploy the app to your actual phone device through VS 2010 and Zune make certain you unplug or close Zune first before attempting to play sound otherwise they will fail to load. You can play sounds without this problem if you run your app in the emulator.
The following code gives and example of playing sound through the MediaElement:
MainPage.xaml:
<MediaElement x:Name="MainME" AutoPlay="False" MediaOpened="MainME_MediaOpened" MediaFailed="MainME_MediaFailed"></MediaElement>
MainPage.xaml.cs:
private void SoundBtn_Click(object sender, RoutedEventArgs e)
{
MainME.Source = new Uri("sounds/mySound.mp3", UriKind.Relative);
MainME.Position = new TimeSpan(0);
}
private void MainME_MediaOpened(object sender, RoutedEventArgs e)
{
MainME.Play();
}
Thanks,
–Mike