Mobile Zone is brought to you in partnership with:

I have worked for several companies as a senior software developer and lead developer. I bave enterprise level programming experience on Web, Silverlight, and Windows Phone 7. I am a MVP in Device Application Development since 2011. Jevgeni has posted 40 posts at DZone. You can read more from them at their website. View Full User Profile

Creating a simple Media Player for Windows Phone 7

11.24.2011
| 11430 views |
  • submit to reddit
In this tutorial I will create a simple Media Player application for playing various videos (e.g in .wmv format). I am going to use MediaElement control as a media container for a player. I will also create few buttons to control the video media flow (Play, Pause, Stop) and a progress bar showing the current progress. In the end of this lesson I will show an alternative way to play a media stream using MediaPlayerLauncher.

windows phone 7 media player by eugenedotnet

windows phone 7 media player by eugenedotnet

Source code

Additional information

1. Creating a new project

First of all you need to create a new project. To do so open Visual Studio 2010 -> File -> New Project -> select Windows Phone Application there as it is shown on picture bellow.

eugenedotnet creating windows phone 7 project

 

2. Adding icons to solution

Now we need to add three icons for the Media Player: play, pause and stop icon to our Project. You can download icons from here or create your own. Make sure that “Build Action” property is “Content” and “Copy to output directory” property is switched to “Copy if newer“. Check image bellow for better understanding.

icons in solution explorer

 

3. Modifying XAML: Orientation

In MainPage.xaml switch SupportedOrientations attribute of PhoneApplicationPage element to PortraitOrLandscape.

SupportedOrientations="PortraitOrLandscape" Orientation="Portrait"

4. Modifying XAML: ContentGrid

In MainPage.xaml add MediaElement control and Progress Bar control to ContentGrid. Set AutoPlay property of MediaElement to true. Do not forget to add RowDefinitions to grid to make it possible to resize controls automatically in future
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="40" />
    </Grid.RowDefinitions>
    <MediaElement Name="myMediaElement" AutoPlay="True" Grid.Row="0" />
    <ProgressBar Name="pbVideo" Grid.Row="1" />
</Grid>

5. Modifying XAML: ApplicationBar

Next we need to create an ApplicationBar in MainPage.xaml. ApplicationBar will contain 3 buttons to operate with media content: play, pause, stop. I have used the following XAML for that:

<phone:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True" >
        <shell:ApplicationBarIconButton IconUri="/icons/play.png" Click="Play_Click"  Text="Play"/>
        <shell:ApplicationBarIconButton IconUri="/icons/pause.png" Click="Pause_Click"  Text="Stop"/>
        <shell:ApplicationBarIconButton IconUri="/icons/stop.png" Click="Stop_Click" Text="Stop"/>
    </shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>

6. Adding functionality

Finally, we have to modify MainPage.xaml.cs file to add functionality for events. The code is very simple so I will not describe it in details. Pay attention that I have used DispatcherTimer object to update the progress bar.

public partial class MainPage : PhoneApplicationPage
{
    // varibles and properties
    DispatcherTimer currentPosition = new DispatcherTimer();
 
    // Constructor
    public MainPage()
    {
        InitializeComponent();
        this.Loaded += new RoutedEventHandler(MainPage_Loaded);
    }
 
    void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        myMediaElement.MediaOpened += new RoutedEventHandler(myMediaElement_MediaOpened);
        myMediaElement.MediaEnded += new RoutedEventHandler(myMediaElement_MediaEnded);
        myMediaElement.CurrentStateChanged += new RoutedEventHandler(myMediaElement_CurrentStateChanged);
        currentPosition.Tick += new EventHandler(currentPosition_Tick);
 
        myMediaElement.Source = new Uri("http://ecn.channel9.msdn.com/o9/ch9/4807/574807/ISWPE05SLToolKitForWP_ch9.wmv", UriKind.Absolute);
    }
 
    void myMediaElement_CurrentStateChanged(object sender, RoutedEventArgs e)
    {
        if (myMediaElement.CurrentState == MediaElementState.Playing)
        {
            currentPosition.Start();
            ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = false; // play
            ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = true;  // pause
            ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = true;  // stop
        }
        else if (myMediaElement.CurrentState == MediaElementState.Paused)
        {
            currentPosition.Stop();
            ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = true; // play
            ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = false;  // pause
            ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = true;  // stop
        }
        else
        {
            currentPosition.Stop();
            ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = true; // play
            ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = false;  // pause
            ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = false;  // stop
        }
    }
 
    void myMediaElement_MediaEnded(object sender, RoutedEventArgs e)
    {
        myMediaElement.Stop();
    }
 
    void myMediaElement_MediaOpened(object sender, RoutedEventArgs e)
    {
        pbVideo.Maximum = (int)myMediaElement.NaturalDuration.TimeSpan.TotalMilliseconds;
        myMediaElement.Play();
    }
 
    void currentPosition_Tick(object sender, EventArgs e)
    {
        pbVideo.Value = (int)myMediaElement.Position.TotalMilliseconds;
    }
 
    private void Play_Click(object sender, EventArgs e)
    {
        myMediaElement.Play();
    }
 
    private void Pause_Click(object sender, EventArgs e)
    {
        myMediaElement.Pause();
    }
 
    private void Stop_Click(object sender, EventArgs e)
    {
        myMediaElement.Stop();
    }
 
}

Alternative way: Using MediaPlayerLauncher

Another way to open a media stream is using MediaPlayerLauncher. This class is located in Microsoft.Phone.Tasks namespace. To open Media stream using MediaPlayerLauncher you simply need to specify the Media property and call Show() method (check code bellow).

MediaPlayerLauncher mediaPlayerLauncher = new MediaPlayerLauncher() { Media = new Uri("http://ecn.channel9.msdn.com/o9/ch9/4807/574807/ISWPE05SLToolKitForWP_ch9.wmv", UriKind.Absolute) };
mediaPlayerLauncher.Show();

Right after Show method is called a Windows Phone Media Player application will open displaying the specified video. The result will look similar to image bellow. If you click on hardware back button you will be navigated back to your application.



Source: http://www.eugenedotnet.com/2010/09/w12-creating-a-simple-media-player-for-windows-phone-7/

Published at DZone with permission of its author, Jevgeni Tšaikin.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Prakash Heda replied on Mon, 2011/11/28 - 1:43am

nice article...what I am looking to see if this player can play video playlist (video's one by one automatically like a mp3 playlist)?

 This is a big feature miss from MS and I am not sure why is that happenend? i wuld appreciate if you know any media player which can play a video playlist... 

Anil Kumar replied on Fri, 2013/04/05 - 2:01am in response to: Prakash Heda

how to apply Next Previous button for playing next and previous songs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace PhoneApplication{publicpartialclassMainPage:PhoneApplicationPage{// ConstructorpublicMainPage(){InitializeComponent();WebClient webClient =newWebClient();
            webClient.DownloadStringCompleted+=newDownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
            webClient.DownloadStringAsync(newUri("http://182.71.215.163:8080/sportal/spice?opid=2541&ani=734446665&src=ODP&event_type=top10&utype=http&aformat=mp3"));}void webClient_DownloadStringCompleted(object sender,DownloadStringCompletedEventArgs e){var rootObject =JsonConvert.DeserializeObject<RootObject>(e.Result);
           songslist.ItemsSource= rootObject.Top10;}privatevoid lstSons_SelectionChanged(object sender,SelectionChangedEventArgs e){(Application.CurrentasApp).selectedSongsItem = songslist.Items[songslist.SelectedIndex]asSongsItem;NavigationService.Navigate(newUri("/Page1.xaml",UriKind.Relative));}}}

This class B where am playing each Songs on its Item clcik

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using Microsoft.Phone.Shell;
using System.Windows.Threading;

namespace PhoneApplication{publicpartialclassPage1:PhoneApplicationPage{DispatcherTimer currentPosition =newDispatcherTimer();publicPage1(){InitializeComponent();Loaded+=newRoutedEventHandler(Page1_Loaded);}voidPage1_Loaded(object sender,RoutedEventArgs e){PhoneApplication.SongsItem selectedSongsItem =(Application.CurrentasApp).selectedSongsItem;string strURI = selectedSongsItem.StreamingURL;
             myMediaElement.MediaOpened+=newRoutedEventHandler(myMediaElement_MediaOpened);
            myMediaElement.MediaEnded+=newRoutedEventHandler(myMediaElement_MediaEnded);
            myMediaElement.CurrentStateChanged+=newRoutedEventHandler(myMediaElement_CurrentStateChanged);
            currentPosition.Tick+=newEventHandler(currentPosition_Tick);

            myMediaElement.Source=newUri(strURI,UriKind.Absolute);}void myMediaElement_CurrentStateChanged(object sender,RoutedEventArgs e){if(myMediaElement.CurrentState==MediaElementState.Playing){
            currentPosition.Start();((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled=false;// play((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled=true;// pause((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled=true;// stop}elseif(myMediaElement.CurrentState==MediaElementState.Paused){
            currentPosition.Stop();((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled=true;// play((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled=false;// pause((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled=true;// stop}else{
            currentPosition.Stop();((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled=true;// play((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled=false;// pause((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled=false;// stop}}void myMediaElement_MediaEnded(object sender,RoutedEventArgs e){
        myMediaElement.Stop();}void myMediaElement_MediaOpened(object sender,RoutedEventArgs e){
        pbVideo.Maximum=(int)myMediaElement.NaturalDuration.TimeSpan.TotalMilliseconds;
        myMediaElement.Play();}void currentPosition_Tick(object sender,EventArgs e){
        pbVideo.Value=(int)myMediaElement.Position.TotalMilliseconds;}privatevoidPlay_Click(object sender,EventArgs e){
        myMediaElement.Play();}privatevoidPause_Click(object sender,EventArgs e){
        myMediaElement.Pause();}privatevoidStop_Click(object sender,EventArgs e){
        myMediaElement.Stop();}}}

NOw i want take 2 Button One for previous songs play and another for Next Songs play But am Unable to this please help me how i will call Next and Previous songs Streming URL please Implement this.Thanx

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.