Tutorials » Silverlight tutorials »

How to play audio or sound files from Silverlight


This sample shows how to play an audio file from Silverlight controls.


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 <Application Name>Code: 3001
Category: MediaError
Message: AG_E_INVALID_FILE_FORMAT


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.SetSource(stream);
media.AutoPlay = false;

media.Stop();
media.Play();


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.

In the above code, "MyNamespace" represents the namespace of your application. "Sound1.wav" is the name of the audio file, assuming the file is located in the root of the application. If the file is within a sub directory, you may have to include the directory name as well, separated by a period.


media.SetSource(stream);

In the above line, we are setting the source for the media player.


media.AutoPlay = false;

The above line says that the player should not play the audio until we explicitly start it to play.


media.Stop();
media.Play();

In the above code, you can see that I am doing a .Stop() before .Play(). The Stop is required only if you have to play the same MediaElement more than once.





Next Chapter: How to display custom Rightclick context menu in Silverlight controls?
Previous Chapter: Display Tooltip for Silverlight controls
More Chapters: Silverlight Tutorials
More Tutorials: Tutorial Index



Top Contributors
Today
    Last 7 Daysmore...

    Awards & Gifts

    Online Members

    More...
     
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India