How to play audio or sound files from Silverlight?


Silverlight provides a class called MediaElement which can be used to play audio or video files.

Silverlight MediaElement supports playing video/audio files in MP3 and WMV formats. The current version of Silverlight does not support .WAV files and .AVI files.
If you attempt to use .WAV or .AVI files with the MediaElement control, you will get the following error:

Error: Unhandled Error in Silverlight 2 Application Code: 3001

Category: MediaError

In order to play an .MP3 or .WMV file, you must first include the file in your Silverlight project and then set it as an Embedded Resource.
In order to make an audio file an embedded resource, right click on the file in your project and select ‘properties’. Then set the ‘Build Action’ as ‘Embedded Resource. This will make the audio file embedded in to your .XAP file when compiled.
Once you make the audio file as an embedded resource, you can play the file either by defining the MediaElement within your XAML or by using the code. Here is the sample code to play an audio file:
MediaElement media = new MediaElement();
Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyNamespace.Sound1.wav");
media.AutoPlay = false;
Let us analyze the code.
Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyNamespace.Sound1.wav");
The above line retrieves the audio stream from the executing assembly. Remember that the audio file is embedded in to the assembly since we set the Build Action as 'Embedded Resource.