MediaElement, MediaPlayerLauncher and ApplicationBar in Windows Phone

Today, I'll write about creating a simple app that plays media using the MediaElement control, uses the ApplicationBar control for the media controls, and also allows use of the MediaPlayerLauncher. 

The application bar icons used can be downloaded for free at: https://www.microsoft.com/downloads/details.aspx?FamilyID=369b20f7-9d30-4cff-8a1b-f80901b2da93 

First, create a new Windows Phone Application project.  Add the files for the ApplicationBar icons to the project for play and pause, and change their Build Action to "Content".

 

Then update the xaml MainPage.xaml to add a MediaElement and the ApplicationBar:

    <Grid x:Name="LayoutRoot" Background="Transparent">

        <Grid.RowDefinitions>

            <RowDefinition Height="*"/>

        </Grid.RowDefinitions>

        <MediaElement Source="https://www.rickytan.net/media/Butterfly.wmv" AutoPlay="True" x:Name="mediaElement1" />

    </Grid>

    <phone:PhoneApplicationPage.ApplicationBar>

        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">

            <shell:ApplicationBarIconButton x:Name="appbar_button1" IconUri="appbar.transport.play.rest.png" Text="Play" Click="appbar_button1_Click"/>

            <shell:ApplicationBarIconButton x:Name="appbar_button2" IconUri="appbar.transport.pause.rest.png" Text="Pause" Click="appbar_button2_Click"/>

            <shell:ApplicationBar.MenuItems>

                <shell:ApplicationBarMenuItem x:Name="menuItem1" Text="Media Player Launcher" Click="menuItem1_Click" />

            </shell:ApplicationBar.MenuItems>

        </shell:ApplicationBar>

    </phone:PhoneApplicationPage.ApplicationBar>

 

Finaly, update the code in MainPage.xaml.cs to hook up the Play, Pause and MediaPlayerLauncher events:

        MediaPlayerLauncher mediaPlayerLauncher;

        public MainPage()

        {

            InitializeComponent();

            mediaPlayerLauncher = new MediaPlayerLauncher();

        }

        private void appbar_button1_Click(object sender, EventArgs e)

        {

            mediaElement1.Play();

        }

        private void appbar_button2_Click(object sender, EventArgs e)

        {

            mediaElement1.Pause();

        }

        private void menuItem1_Click(object sender, EventArgs e)

        {

            mediaPlayerLauncher.Media = new Uri("https://www.rickytan.net/media/Butterfly.wmv", UriKind.Absolute);

            mediaPlayerLauncher.Show();

        }

 

 To enable the app to run in landscape mode, change the SupportedOrientations in MainPage.xaml to PortraitOrLandscape: 

SupportedOrientations="PortraitOrLandscape"