Playing media content on Windows Phone 7 with MediaElement
Join the DZone community and get the full member experience.
Join For FreeUltimately, this article started from a simple question - how is it possible to play a media file on Windows Phone 7? There are two ways to play existing media content. The developer has to either use the system player (given that the media content is stored in the media library), or use the MediaElement control.
MediaElement might be a bit tricky, but it's not that hard as it seems. First thing that has to be done is creating a new instance of the control. Starting with XAML is a good idea, even if you decide to only define the basic "skeleton":
Now that you have it, it's time to set the source for the control. In the code-behind, I decided to set up a sample playback mechanism that is triggered on startup. So in the page constructor I include a reference to the Loaded event handler.
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
In the event handler itself, I am going to actually set the Source property for the MediaElement so I actually have a media file to play.
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
mediaPlayer.Source = new Uri("/Canyon.mp3", UriKind.Relative);
mediaPlayer.Play();
}
Here I am showing the easiest and least common scenario - the file is bundled with the application and all you do is play it from inside the package (notice that the file is copied as Content).
Media content can also be loaded from online sources. For example:
mediaPlayer.Source = new Uri("http://www.robtowns.com/music/blind_willie.mp3", UriKind.Absolute);
mediaPlayer.Play();
But that is generally not enough, and developers want to attach additional functionality, like the possibility to show the progress of the current playback process. This can be easily done with a ProgressBar control, but first you would have to know the natural duration of the track.
Here comes the issue - for tracks that are obtained from online sources, the natural duration can only be obtained when the track finished buffering. Luckily, there is the BufferingProgressChanged event handler that allows keeping track of the buffering process. The primary indicator that buffering is complete is the fact that the BufferingProgress property is set to 1.
void mediaPlayer_BufferingProgressChanged(object sender, RoutedEventArgs e)
{
MediaElement m = (MediaElement)sender;
if (m.BufferingProgress == 1)
Debug.WriteLine(m.NaturalDuration);
}
Given that the user knows when the song is buffered, it would also be pretty cool to see the song playing progress - how much of the actual media content was played. In order to do this, I created a separate property inside the main page and linked it to a DependencyProperty, so I can bind to it:
DependencyProperty property = DependencyProperty.Register("Progress", typeof(double), typeof(PhoneApplicationPage), new PropertyMetadata(0.0));
public double Progress
{
get
{
return (double)GetValue(property);
}
set
{
SetValue(property, value);
}
}
The ProgressBar control itself is explicitly defined in the page XAML:
<ProgressBar x:Name="mainBar" Height="20" Width="400" Value="{Binding ElementName=Main,Path=Progress}"></ProgressBar>
Main is the name of the current page (that is hosting the ProgressBar). So where exactly would I be checking the time? There is no Playing event, but there is a CurrentState property that shows what the player is doing. In this case, I can link a new event handler:
mediaPlayer.CurrentStateChanged += new RoutedEventHandler(mediaPlayer_CurrentStateChanged);
Inside the event handler itself, I am checking the current state of the player and if it is set to Playing, I will get the duration of the currently loaded media content and calculate the percentage against it:
void mediaPlayer_CurrentStateChanged(object sender, RoutedEventArgs e)
{
if (mediaPlayer.CurrentState == MediaElementState.Playing)
{
Duration = mediaPlayer.NaturalDuration.TimeSpan.TotalSeconds;
ThreadPool.QueueUserWorkItem(o =>
{
while (true)
{
Dispatcher.BeginInvoke(new Action(() => Progress = mediaPlayer.Position.TotalSeconds * 100 / Duration));
Thread.Sleep(0);
}
});
}
}
I am doing this in a separate thread so there will be almost no performance footprint on the UI (and so that the ProgressBar is actually updated). Here, Duration is a simple property of type double.
public double Duration { get; set; }
Notice that whenever I am getting the NaturalDuration or Position, I am retrieving TotalSeconds instead of Seconds. That's because Seconds will return the number of seconds in the actual play time (given that there are also minutes and hours present). So, for example, if I am loading a song that has a duration of 2:16, Seconds will return 16 when in fact there are 136 seconds total. Same applies to Position, that returns the played time.
When I am testing the above code on the sample song I am loading, here is what I get:
Once the media is loaded, it is possible to use the Pause, Stop and Play methods to control the playback.
Opinions expressed by DZone contributors are their own.
Trending
-
Integration Testing Tutorial: A Comprehensive Guide With Examples And Best Practices
-
What Is Envoy Proxy?
-
Generics in Java and Their Implementation
-
How AI Will Change Agile Project Management
Comments