Saturday, 12 July 2014

Playing Video in Windows Store App Using C#

Introduction
In a Windows 8 Apps we can also play a video file using the Media Element control of Windows 8 Apps. To play videos in a Windows 8 Apps we use the MediaElement class. We can play audio and video using the HTML5 audio and video tags, or using C#. The Media Element class has many properties and methods that create media more attractively. It provides the options of play, pause, forward etc. To play video files we have set the source to the media file to play. We can set the source at the design time or by selecting from the local system using the FileOPenPicker class.

In this article we create a page that plays a video file with various buttons such as Play, Pause, Forward and Normal. We use the FileOpenPicker class to open a local media file and play it using the Media Element with various options.

Steps to be followed:

Step1: To create a new Windows Store project:
  • Start Visual Studio 2012.
  • Select File > New Project. The New Project dialog box opens.
  • Select the Windows Store template.
  • In the center pane, select Blank Application.
  • Enter a name for the project.
  • Click OK. Your project files are created
Select-Windows-8-apps.jpg

Step 2: Create a MediaElement in the MainPage.xaml page and give it a Name. Set the height and width of the element.
<Page
    x:Class="media.MainPage"
    IsTabStop="false"
    xmlns:local="using:media"
    mc:Ignorable="d">

    <Grid Margin="20,50">
        <Grid.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black"/>
                <GradientStop Color="#FFC5947D" Offset="1"/>
            </LinearGradientBrush>
        </Grid.Background>

        <StackPanel x:Name="content" Margin="120,40,-10,0">
            <MediaElement DefaultPlaybackRate="0.5"  x:Name="media" HorizontalAlignment="Left" Height="442" VerticalAlignment="Top" Width="877" Margin="165,150,0,0"/>
        </StackPanel>
      <Button x:Name="select" Click="b_Click_1" Height="63"  Width="229" Content="Select Media file" Margin="24,35,0,576"></Button>
      <Button x:Name="play" Click="play_Click_1"  Height="63" Width="177" FontSize="15"Content="Play" Margin="47,109,0,496"/>
      <Button x:Name="pause" Click="stop_Click_1"  Height="63" Width="177" FontSize="15"Content="Pause" Margin="47,198,0,407"/>
     <Button x:Name="btnForward" Click="btnForward_Click"  Content="Forward" Height="63"Width="177"  FontSize="15" Margin="47,283,0,322" />
     <Button x:Name="normal" Click="normal_Click_1"  Height="63" Width="177" FontSize="15"Content="Normal" Margin="47,369,0,236"/>
   </Grid>
</Page>

Step 3: Include the following namespaces in the MainPage.xaml.cs file:
 
using Windows.Storage.Pickers;
using Windows.Storage;

Step 4: Then, we use the FileOpenPicker class to select a media file from the user in the MainPage.xaml.cs file:
private async void b_Click_1(object sender, RoutedEventArgs e)
{
     var openPicker = new FileOpenPicker();
     openPicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
     openPicker.FileTypeFilter.Add(".wmv");
     openPicker.FileTypeFilter.Add(".mp4");
     var file = await openPicker.PickSingleFileAsync();
     var stream = await file.OpenAsync(FileAccessMode.Read);
     / mediaControl is a MediaElement defined in XAML
     media.SetSource(stream, file.ContentType);
     media.Play();
}

In the above code we use the FileOpenPicker class. We set the SuggestedStartLocation properties that specify the default location of where the user selects the media file from and the FileTypeFilter properties that specify the type of media file to be play by the Media Element. Here we use Async Calling to pick a file and give the stream of the file to the setSource properties of MediaElement.

Step 5: Then, we provide code for the various buttons that we have created:
 
private void btnForward_Click(object sender, RoutedEventArgs e)
{
    media.DefaultPlaybackRate = 2.0;
    media.Play();
}
private void stop_Click_1(object sender, RoutedEventArgs e)
{
    media.Pause();
}
private void normal_Click_1(object sender, RoutedEventArgs e)
{
    media.DefaultPlaybackRate = 0.5;
    media.Play();
}
private void play_Click_1(object sender, RoutedEventArgs e)
{
    media.Play();
}

Step 6: 
The full code is here that enables the user to choose a file from the local system and play it with various control options:
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.Pickers;
using Windows.Storage;

namespace media
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }
       private async void b_Click_1(object sender, RoutedEventArgs e)
        {
            var openPicker = new FileOpenPicker();
            openPicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
            openPicker.FileTypeFilter.Add(".wmv");
            openPicker.FileTypeFilter.Add(".mp4");
            var file = await openPicker.PickSingleFileAsync();
            var stream = await file.OpenAsync(FileAccessMode.Read);
            // mediaControl is a MediaElement defined in XAML
            media.SetSource(stream, file.ContentType);
            media.Play();
         }
        private void btnForward_Click(object sender, RoutedEventArgs e)
        {
            media.DefaultPlaybackRate = 2.0;
            media.Play();
        }
        private void stop_Click_1(object sender, RoutedEventArgs e)
        {
            media.Pause();
        }
        private void normal_Click_1(object sender, RoutedEventArgs e)
        {
            media.DefaultPlaybackRate = 0.5;
            media.Play();
        }
        private void play_Click_1(object sender, RoutedEventArgs e)
        {
            media.Play();
        }
    }
}

Step 7:
 Press F5 to run the program. Click the "Select Media File" button to select the file to be played:

Media-Element-In-Windows8-Apps.jpg

Step 8: Select Media file from the local system drives and click "Open" button.

File-Upload-In-Windows8-Apps.jpg

Step 9: The media is playing on the Media Element control on the page.
 The user can use various control options to pause, play, forward and normal buttons. When the user clicks on the "Pause" button the video is paused until the user plays it again.
If we want to fast forward a video then we click on the "Forward" button. To return to normal speed click the "Normal" button.


Playing-Video-file-In-Windows8-Apps.jpg

Tuesday, 8 July 2014

Using a MediaElement in Windows Phone App

I will assume that you have installed the tools for working like Visual Studio 2012 ( or 2013 ) and that you’re on Windows 8 at least ( or 8.1 )  .
In this workshop we will learn to use a MediaElement in our Windows Phone application .
We will begin with setting up our XAML code , we will use two buttons for a Playing and Stoping , and a slider for the volume and of course a MediaElement :

1

Let’s move now to the C# code and get our MediaElement to run , we will need aDispatcherTimer : it’s a timer which is processed at a specified interval of time and at a specified priority. Also we will ned to configure our MediaElement depending on the MediaOpened or Stopped , it will be like this :

2


We will set up now the source of our sound and code the eventhandlers for the click on the two buttons : 3

We will be set up the code for the slider right now and control the volume with some C# code :

4

Run your project and you click run and the MediaElement will play the sound that you already used , you can use a local MP3 file also , you just need to set up the right path in the code .

Transfering multiple data between pages in Visual Studio

I will assume that you have installed the tools for working like Visual Studio 2012 ( or 2013 ) and that you’re on Windows 8 at least ( or 8.1 ) .
In this workshop we will be transfering multiple data between pages in our Windows Phone application . We will be using new elements in the XAML code and using C# Classes .
Go ahead and create a new project , then follow these steps :
We will be working with Angry Birds today and handel their transfer between pages , so we will create a C# class named Bird that we will use during all the workshop : Right click on the project –> Add –>Class
Capture
We will add now a new class called SharedInformation that will contain all the informations that pages will be sharing .
Capture

Now add a new page to your application : Right click on the project —>Add—>New Item —> Windows Phone Portrait Page , then name it SecondPage.xaml
We will start now handeling the transfer of the data :
We will add a new XAML element which is listbox
Capture
Then we need to add some C# code to be able to work with the listbox , let’s add this code in the MainPage.xaml.cs
Capture
Let’s explain now what we are doing :
This listbox will contain multiple images of angry birds , you will select more than one bird and navigate to the second page and in this second page you will find what you’ve already choosen .
So here’s how things work :
We are preforming a Binding on this listbox to get elements
The image we’re using has also a Binding to the proprety imagePath
The textblock is binded also to the proprety name .
The whole workshop is based on a single line of code that will handle the link and transfer of the data , this line of code is : birdList.datacontext= birds;
We will now add a big feature in Windows Phone which is the application bar , we will have a workshop about application bar and how we use it but it’s not a big problem you can just use the code written here and will understand the concept .
Capture
We’ve added some images in the Assets of the application and add an event on each click of each button of the application bar .
Now let’s add the code behind of these events .
Capture

In this event we will learn how to navigate between pages in Windows Phone , this navigation will happen with this line of code :
 NavigationService.Navigate(new Uri(“/SecondPage.xaml”, UriKind.RelativeOrAbsolute));
We will move now to the SecondPage.xaml and an event on the load of the application , we can add this using XAML :
Capture

You can notice in the last line that we’ve added Loaded which is an event for the phone application page load , we will add now the C# code of this event :
Capture

Before running this project , just make sure that you’ve added some pictures in the Assets because I’ve used the angry birds pictures here .
Save the project and run and enjoy transfering multiple data between these two pages .

Working with Row and Column Definitions in XAML

I will assume that you have installed the tools for working like Visual Studio 2012 ( or 2013 ) and that you’re on Windows 8 at least ( or 8.1 ) .
In this workshop we will be working with a big part for coding on Windows Phone which is the XAML code .  The XAML code helps us to handle everything that exists on the application like Buttons , TextBlocks , Images .
Here’s an example of XAML code that uses a Grid :
Capture
During this Workshop we learn together how to use all the space available in the screen of the Windows Phone and devide it into 4 parts . This will help us in developping any application to organize our contents .
Go Ahead and create a New Project , then follow these steps :
In the main Grid which is Content Panel add these lines :
Capture

With these lines we ‘ve made our Grid with 2 rows and 2 columns , we will see now how we can have access to each “box” of the Grid .
We will add a Button now with this code , I recommend you to type this code by yourself to experience the XAML , don’t preform a Drag and Drop :

Capture

You can notice that I gave the Button a name as Btn1 which is one of the best practises to organize our code behind and have accessto multiple Buttons .
Content will contain the content of the Button , we used 1 here .
Foreground is for the color of the content of the Button , I gave it here a StaticResource which is PhoneAccentBrush , this will help us to get the color of the theme on the Windows Phone ( you can check this if you have a device )
The important part here is Grid.Column and Grid.Row , I’ve given the Button a specific place in our Grid , it will be in the (0,0) position.
We will add now 3 other Buttons and change their position as usual :
Capture

We will work now on the code behind for each event  , we are trying to show a number for every Button clicked , we will add this code for each event now :

Capture

You can save your work and run the application now , you will see that on every click on a Button you will have its number shown . This helps us to learn how to devide the Grid and use multiple Button in one Grid using the XAMl code .

Working with ApplicationBar in Visual Studio 2013 in Windows Phone 8

create a new project (Windows Phone 8 Blank App Silverlight) , then follow these steps :
In the MainPage.xaml , go to the bottom of the page and add these lines of code and watch what’s happening :

Capture

We will add now for each button an event as we did in the previous workshops :
Capture

The most important thing in this workshop is to be able to handle the application bar not the events , as you can notice here I’ve added  two buttons and two menu items , you can add up to 4 buttons and assign them with application bar images and it will look like this :
IC531092

If you’re wondering how to get these pictures , go to Program Files –>Microsoft SDK’s —>Windows Phone–>V8.0–>Icons and you will find Dark and Lignt icons there :
Capture