In this post I will explain you how to play a media file in Windows phone app using Media element control.
Using the MediaElement is an easier way to play sound in Windows Phone. Just add the MediaElement control to your Page and set the source file path and set the AutoPlay property of the MediaElement to true. You will see that your Windows Phone App page when run, will automatically play the sound. But if you want to play it manually you can set the AutoPlay property to false and should call the play method of MediaElement.
1. Create a new Project having the name Mediacontrol.
2. Now drag and drop MediaElement control form toolbox into MainPage.xaml design page.
3. After this set its name property to mycontrol. You can also set the media path by selecting Source property of MediaElement control in Xaml Window and AutoPlay property to False.
4. Now if you want to play the music file automatically as the page opens you can set the AutoPlay property of MediaElement to true. By default the AutoPlay property is true.
5. You can control media playback by using the Play, Pause, and Stop methods of a MediaElement object.
Add three buttons to the MainPage.xaml having the Content property value play, pause and stop.
6. The code for click event handlers of these buttons is given below.
7. Now run the application on emulator and click on play button. You will hear an audio clip.
8. You can also change the source property of media element dynamically using c#. For example you are building a ringtone application in which there are no of music files so you may want to play these files individually using a single media element control.
Suppose the audio file is having the name 2.mp3 and is present in root folder.
So the source property of control is given as
9. You can specify the volume of the MediaElement object’s audio as a value from 0 to 1, with 1 being the loudest using Volume property of Media Element. The default value is 0.5.
Note: All audio file formats are not supported on Windows phone. You can check the list of audio formats supported by Windows phone from the link given below.
10. I hope this post will be helpful to you. You can download the full project source file from the link given below.