Making a Video App in Window Store Apps

Introduction

Today we are creating a simple Video App in Windows Store apps using C# and XAML.  In this video app we have the full functionality to play videos, such as play, pause, volume, full screen etc. To create this video app we are using the three namespaces "Windows.storage" and "Windows.storage.pickers" for picking a file from the local drive and "Windows.UI.popups" to display a warning message.

Step 1

Start Visual Studio 2012 and start a new Windows Store apps project.

Start-Project-Windows-Store-Apps.jpg

Step 2

Go to Solution Explorer and double-click on "MainPage.xaml".

Solution-Explorer-Windows-Store-Apps.jpg

Step 3

Your "MainPage.xaml" is as the following code:

<Page

    x:Class="VideoPlayer.MainPage"

    IsTabStop="false"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:local="using:VideoPlayer"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    mc:Ignorable="d"

    Loaded="Page_Loaded_1">

 

    <Page.Resources>

        <Style x:Name="ControlStyle"  TargetType="Button">

            <Setter Property="Height" Value="40" />

            <Setter Property="Width" Value="100" />

            <Setter Property="FontSize" Value="11" />

            <Setter Property="BorderBrush" Value="White"/>

        </Style>

    </Page.Resources> 

    <Grid Background="#FF3C3C3A">

        <Grid.RowDefinitions>

            <RowDefinition Height="*"/>

            <RowDefinition Height="100"/>

        </Grid.RowDefinitions>

        <ContentControl x:Name="FullScreen" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"  Height="400"

        Grid.Row="0" KeyUp="FullScreen_KeyUp" Margin="10,346,-10,22" Grid.RowSpan="2" >

            <MediaElement Name="MyMedia" MediaOpened="MyMedia_MediaOpened_1" MediaEnded="MyMedia_MediaEnded_1"  

            MediaFailed="MyMedia_MediaFailed_1" CurrentStateChanged="MyMedia_CurrentStateChanged_1"  AutoPlay="False" />

        </ContentControl>

        <StackPanel Name="TransportControlsPanel" HorizontalAlignment="Center"                     

                   Grid.Row="1" >

            <Slider x:Name="TimelineSlider" Margin="10,0" Width="800" ValueChanged="TimelineSlider_ValueChanged"

            PointerEntered="TimelineSlider_PointerEntered" PointerCaptureLost="TimelineSlider_PointerCaptureLost" Background="#29080808" />

            <StackPanel Orientation="Horizontal">

                <Button x:Name="Open"

                   Style="{StaticResource ControlStyle}" Content="Open" Click="Open_Click"/>

                <Button x:Name="BtnPlay"

                   Style="{StaticResource ControlStyle}" Content="Play" Click="BtnPlay_Click" />

                <Button x:Name="BtnPause"

                   Style="{StaticResource ControlStyle}" Content="Pause" Click="BtnPause_Click" />

                <Button x:Name="BtnStop"

                   Style="{StaticResource ControlStyle}" Content="Stop" Click="BtnStop_Click" />

                <Button x:Name="btnReverse"

                   Style="{StaticResource ControlStyle}" Content="Rewind" Click="btnReverse_Click" />

                <Button x:Name="btnForward"

                   Style="{StaticResource ControlStyle}" Content="Forward" Click="btnForward_Click" />

                <Button x:Name="btnMute"

                   Style="{StaticResource ControlStyle}" Content="Mute" Click="btnMute_Click" />

                <Button x:Name="btnFullScreen"

                   Style="{StaticResource ControlStyle}" Content="FullScreen" Click="btnFullScreen_Click" />

                <Button x:Name="btnVolumeUp"

                   Style="{StaticResource ControlStyle}" Content="Vol-" Click="btnVolumeUp_Click" />

                <Button x:Name="btnVolumeDown"

                   Style="{StaticResource ControlStyle}" Content="Vol+" Click="btnVolumeDown_Click" />

                <TextBlock x:Name="txtVolume" FontSize="14"

                   Text="{Binding Volume, ElementName=videoMediaElement}"

                   VerticalAlignment="Center" HorizontalAlignment="Right"  />

            </StackPanel>

        </StackPanel>

    </Grid>

</Page>

Step 4

Your "MainPage.xaml.cs" page is as the following code:

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using Windows.Foundation;

using Windows.Foundation.Collections;

using Windows.UI.Xaml;

using Windows.UI.Xaml.Controls;

using Windows.UI.Xaml.Controls.Primitives;

using Windows.UI.Xaml.Data;

using Windows.UI.Xaml.Input;

using Windows.UI.Xaml.Media;

using Windows.UI.Xaml.Navigation;

using Windows.Storage;

using Windows.Storage.Pickers;

using Windows.UI.Popups;

 

namespace VideoPlayer

    public sealed partial class MainPage : Page

    {

        public MainPage()

        {

            this.InitializeComponent();

        } 

        private bool isFullscreenToggle = false;

        public bool IsFullscreen

        {

            get { return isFullscreenToggle; }

            set { isFullscreenToggle = value; }

        }

        private Size previousVideoContainerSize = new Size();

 

        private void FullscreenToggle()

        {

            this.IsFullscreen = !this.IsFullscreen;

 

            if (this.IsFullscreen)

            {

                TransportControlsPanel.Visibility = Visibility.Collapsed;

                previousVideoContainerSize.Width = FullScreen.ActualWidth;

                previousVideoContainerSize.Height = FullScreen.ActualHeight; 

                FullScreen.Width = Window.Current.Bounds.Width;

                FullScreen.Height = Window.Current.Bounds.Height;

                FullScreen.Width = Window.Current.Bounds.Width;

                FullScreen.Height = Window.Current.Bounds.Height;

            }

            else

            {

                TransportControlsPanel.Visibility = Visibility.Visible;

                FullScreen.Width = previousVideoContainerSize.Width;

                FullScreen.Height = previousVideoContainerSize.Height;

                FullScreen.Width = previousVideoContainerSize.Width;

                FullScreen.Height = previousVideoContainerSize.Height;

            }

        } 

        private void MainPage_Loaded(object sender, RoutedEventArgs e)

        {

            TimelineSlider.ValueChanged += TimelineSlider_ValueChanged;

            PointerEventHandler pointerpressedhandler = new PointerEventHandler(TimelineSlider_PointerEntered);

            TimelineSlider.AddHandler(Control.PointerPressedEvent, pointerpressedhandler, true); 

            PointerEventHandler pointerreleasedhandler = new PointerEventHandler(TimelineSlider_PointerEntered);

            TimelineSlider.AddHandler(Control.PointerCaptureLostEvent, pointerreleasedhandler, true);

        } 

        protected override void OnNavigatedTo(NavigationEventArgs e)

        {

 

        } 

        private void MyMedia_MediaOpened_1(object sender, RoutedEventArgs e)

        {

            double absvalue = (int)Math.Round(

           MyMedia.NaturalDuration.TimeSpan.TotalSeconds,

            MidpointRounding.AwayFromZero);

            TimelineSlider.Maximum = absvalue;

            TimelineSlider.StepFrequency = SliderFrequency(MyMedia.NaturalDuration.TimeSpan); 

            SetupTimer();

        } 

        private bool sliderpressed = false; 

        private void MyMedia_MediaFailed_1(object sender, ExceptionRoutedEventArgs e)

        {

            string str = GetHresultFromErrorMessage(e);

        } 

        private void MyMedia_CurrentStateChanged_1(object sender, RoutedEventArgs e)

        {

            if (MyMedia.CurrentState == MediaElementState.Playing)

            {

                if (sliderpressed)

                {

                    _timer.Stop();

                }

                else

                {

                    _timer.Start();

                }

            } 

            if (MyMedia.CurrentState == MediaElementState.Paused)

            {

                _timer.Stop();

            } 

            if (MyMedia.CurrentState == MediaElementState.Stopped)

            {

                _timer.Stop();

                TimelineSlider.Value = 0;

            }

        } 

        private void MyMedia_MediaEnded_1(object sender, RoutedEventArgs e)

        {

            StopTimer();

            TimelineSlider.Value = 0.0;

        } 

        private void FullScreen_KeyUp(object sender, KeyRoutedEventArgs e)

        {

            if (IsFullscreen && e.Key == Windows.System.VirtualKey.Escape)

            {

                FullscreenToggle();

            }

            e.Handled = true;

        }

        private void Page_Loaded_1(object sender, RoutedEventArgs e)

        {

 

        } 

        private async void Open_Click(object sender, RoutedEventArgs e)

        {

            try

            {

                var FileOpen = new FileOpenPicker();

                FileOpen.SuggestedStartLocation = PickerLocationId.MusicLibrary;

                FileOpen.FileTypeFilter.Add(".MP4");

                FileOpen.FileTypeFilter.Add(".WMV");

                FileOpen.FileTypeFilter.Add(".AVI");

                var File = await FileOpen.PickSingleFileAsync();

                var Stream = await File.OpenAsync(FileAccessMode.Read);

                MyMedia.SetSource(Stream, File.ContentType);

                MyMedia.Play();

            }

            catch (Exception ex)

            {

                MessageDialog msg = new MessageDialog("Plase Select any media file");

                msg.ShowAsync();

            }

        }

        private void BtnPlay_Click(object sender, RoutedEventArgs e)

        {

            if (MyMedia.DefaultPlaybackRate != 1)

            {

                MyMedia.DefaultPlaybackRate = 1.0;

            }

            MyMedia.Play();

        } 

        private void BtnPause_Click(object sender, RoutedEventArgs e)

        {

            MyMedia.Pause();

        } 

        private void BtnStop_Click(object sender, RoutedEventArgs e)

        {

            MyMedia.Stop();

        } 

        private void btnReverse_Click(object sender, RoutedEventArgs e)

        {

            MyMedia.DefaultPlaybackRate = -2;

            MyMedia.Play();

        }

        private void btnForward_Click(object sender, RoutedEventArgs e)

        {

            MyMedia.DefaultPlaybackRate = 2.0;

            MyMedia.Play();

        }

 

        private void btnMute_Click(object sender, RoutedEventArgs e)

        {

            MyMedia.IsMuted = !MyMedia.IsMuted;

        }

        private void btnFullScreen_Click(object sender, RoutedEventArgs e)

        {

            FullscreenToggle();

        } 

        private void btnVolumeUp_Click(object sender, RoutedEventArgs e)

        {

            if (MyMedia.IsMuted)

            {

                MyMedia.IsMuted = false;

            } 

            if (MyMedia.Volume > 0)

            {

                MyMedia.Volume -= .1;

            }

        } 

        private void btnVolumeDown_Click(object sender, RoutedEventArgs e)

        {

            if (MyMedia.IsMuted)

            {

                MyMedia.IsMuted = false;

            }

            if (MyMedia.Volume < 1)

            {

                MyMedia.Volume += .1;

            }

        } 

        private void TimelineSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)

        {

            if (!sliderpressed)

            {

                MyMedia.Position = TimeSpan.FromSeconds(e.NewValue);

            }

        }

        private void TimelineSlider_PointerEntered(object sender, PointerRoutedEventArgs e)

        {

            sliderpressed = true;

        } 

        private void TimelineSlider_PointerCaptureLost(object sender, PointerRoutedEventArgs e)

        {

            MyMedia.Position = TimeSpan.FromSeconds(TimelineSlider.Value);

            sliderpressed = false;

        } 

        private string GetHresultFromErrorMessage(ExceptionRoutedEventArgs e)

        {

            String hr = String.Empty;

            String token = "HRESULT - ";

            const int hrLength = 10; 

            int tokenPos = e.ErrorMessage.IndexOf(token, StringComparison.Ordinal);

            if (tokenPos != -1)

            {

                hr = e.ErrorMessage.Substring(tokenPos + token.Length, hrLength);

            } 

            return hr;

        } 

        private DispatcherTimer _timer;

        private void SetupTimer()

        {

            _timer = new DispatcherTimer();

            _timer.Interval = TimeSpan.FromSeconds(TimelineSlider.StepFrequency);

            StartTimer();

        } 

        private void _timer_Tick(object sender, object e)

        {

            if (!sliderpressed)

            {

                TimelineSlider.Value = MyMedia.Position.TotalSeconds;

            }

        } 

        private void StartTimer()

        {

            _timer.Tick += _timer_Tick;

            _timer.Start();

        } 

        private void StopTimer()

        {

            _timer.Stop();

            _timer.Tick -= _timer_Tick;

             private double SliderFrequency(TimeSpan timevalue)

        {

            double stepfrequency = -1; 

            double absvalue = (int)Math.Round(timevalue.TotalSeconds, MidpointRounding.AwayFromZero);             

            stepfrequency = (int)(Math.Round(absvalue / 100));

            if (timevalue.TotalMinutes >= 10 && timevalue.TotalMinutes < 30)

            {

                stepfrequency = 10;

            }

            else if (timevalue.TotalMinutes >= 30 && timevalue.TotalMinutes < 60)

            {

                stepfrequency = 30;

            }

            else if (timevalue.TotalHours >= 1)

            {

                stepfrequency = 60;

            } 

            if (stepfrequency == 0) stepfrequency += 1; 

            if (stepfrequency == 1)

            {

                stepfrequency = absvalue / 100;

            }

            return stepfrequency;

        }

    }

}

Step 5

The result window will be as in the following:

 Result-Video-Windows-Store-Apps.jpg


Similar Articles