Universal Windows application: Play a YouTube video
Introduction
Usually when you want to embed a video from YouTube in Universal Windows application, you use WebView.
Therefore, when you use the WebView for displaying a video from YouTube, you can't use your own controls to handle the video (like play button, full screen button...).
That's why this wiki, talks about MyToolkit.Extended.
**MyToolkit.Extended **containing lots of useful classes for various .NET platforms includes the YouTube class. The YouTube class allows to play video from YouTube in your Universal Windows application without using the WebView
Step By Step - Embed YouTube video to Universal Windows application
In this demo we will start from scratch and we will embed YouTube video to a new Universal Windows project.
Step 1: Create new Universal Windows project
Create a new Blank App (Universal Windows) C# project in Visual Studio 2017, and named it YouTubeVideoSample
Step 2: Add MyToolkit package
Open the package manager console
In the package manager console run this command:
Install-Package MyToolkit.Extended
Step 3: Embed the video from YouTube
>> Open your video in YouTube and copy the YouTube Id of your video. In our example, it’s KvKML4TTyjQ
>> In the MainPage.xaml of the project and insert this code:
<Page
x:Class="YouTubeVideoSample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:YouTubeVideoSample"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<MediaElement x:Name="MediaElt"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Width="400"
Height="350" />
</Grid>
</Page>
In the MainPage.xaml.cs, insert this code:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string YouTubeId = "KvKML4TTyjQ";
try
{
YouTubeUri url = await YouTube.GetVideoUriAsync(YouTubeId, YouTubeQuality.Quality360P);
MediaElt.Source = url.Uri;
MediaElt.Play();
}
catch (Exception)
{
// TODO show error (video uri not found)
}
}
Run your application and you will see your YouTube’s video in your Universal Windows application.
That's it!
As you can see, it is very easy to use the MyToolkit.Extended package to play videos from YouTube in a Universal Windows application. Now let's create a video library from YouTube
Create a video library from YouTube
In this part, we are going to create a video library (see image below) from YouTube in a Universal Windows application step by step.
- Create a new folder Models.
- Add the class YouTubeVideo.cs in the Models repository and insert this code:
public class YouTubeVideo
{
public string YouTubeId { get; set; }
public string Title { get; set; }
public Uri ThumbnailUri { get; set; }
public YouTubeUri VideoUri { get; set; }
}
- Open the MainPage.xaml and remove the code below:
<MediaElement x:Name="MediaElt"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Width="400"
Height="350" />
The MainPage.xaml should be like this:
<Page x:Class="YouTubeVideoSample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:YouTubeVideoSample"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
</Grid>
</Page>
- Open the MainPage.xaml.cs and remove the code below:
string YouTubeId = "KvKML4TTyjQ";
try
{
YouTubeUri url = await YouTube.GetVideoUriAsync(YouTubeId,YouTubeQuality.Quality360P);
MediaElt.Source = url.Uri;
MediaElt.Play();
}
catch (Exception)
{
// TODO show error (video uri not found)
}
The MainPage.xaml.cs should be like this:
using MyToolkit.Multimedia;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
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 YouTubeVideoSample.Models;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace YouTubeVideoSample
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
}
}
}
- Open the MainPage.xaml and insert this code below the <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">:
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!--THE PAGE’S TITLE-->
<TextBlock Style="{StaticResource HeaderTextBlockStyle}"
Text="YouTube videos"
Margin="20 20 0 0" />
<ProgressRing IsActive="True"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Grid.Row="1"
Width="75"
Height="75"
x:Name="ProgressRingLoading"
Visibility="Visible" />
<!--CONTENT-->
<Grid Margin="20" Visibility="Collapsed" x:Name="GridContent"
Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid VerticalAlignment="Top"
Margin="0 20 20 20">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<MediaElement x:Name="Player"
AreTransportControlsEnabled="True" />
<TextBlock x:Name="TxtVideoName"
Grid.Row="1"
Style="{StaticResource SubtitleTextBlockStyle}" />
</Grid>
<!--VIDEOS LISTE-->
<ListView x:Name="LVVideos"
Grid.Column="1"
VerticalAlignment="Top"
ItemClick="LVVideos_ItemClick"
SelectionMode="None"
IsItemClickEnabled="True">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Source="{Binding ThumbnailUri}"
Height="250"
Width="250" />
<TextBlock HorizontalAlignment="Center"
VerticalAlignment="Top"
Text="{Binding Title}"
FontSize="11"
TextWrapping="WrapWholeWords" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
The progress ring will be displayed while the videos are loading. It will avoid to show a blank page when the application is displayed.
The property AreTransportControlsEnabled="True" in the MediaElement displays the actions buttons (play, fullscreen…).
- Open the MainPage.xaml.cs and insert this code:
private ObservableCollection<YouTubeVideo> YouTubeVideosCollection;
public MainPage()
{
this.InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
List<YouTubeVideo> YouTubeVideos = await GetYouTubeVideos();
YouTubeVideosCollection = new ObservableCollection<YouTubeVideo>(YouTubeVideos);
LVVideos.ItemsSource = YouTubeVideos;
ProgressRingLoading.Visibility = Visibility.Collapsed;
GridContent.Visibility = Visibility.Visible;
}
/// <summary>
/// Return all YouTube videos
/// </summary>
/// <returns></returns>
private async Task<List<YouTubeVideo>> GetYouTubeVideos()
{
List<YouTubeVideo> LstVideos = new List<YouTubeVideo>()
{
new YouTubeVideo
{
YouTubeId="KvKML4TTyjQ",
Title=await YouTube.GetVideoTitleAsync("KvKML4TTyjQ"),
ThumbnailUri= YouTube.GetThumbnailUri("KvKML4TTyjQ",YouTubeThumbnailSize.Medium),
VideoUri=await YouTube.GetVideoUriAsync("KvKML4TTyjQ",YouTubeQuality.Quality360P)
},
new YouTubeVideo
{
YouTubeId="GIeQEyjGef4",
Title=await YouTube.GetVideoTitleAsync("GIeQEyjGef4"),
ThumbnailUri= YouTube.GetThumbnailUri("GIeQEyjGef4",YouTubeThumbnailSize.Medium),
VideoUri=await YouTube.GetVideoUriAsync("GIeQEyjGef4",YouTubeQuality.Quality360P)
},
new YouTubeVideo
{
YouTubeId="mhZdTqGsI14",
Title=await YouTube.GetVideoTitleAsync("mhZdTqGsI14"),
ThumbnailUri= YouTube.GetThumbnailUri("mhZdTqGsI14",YouTubeThumbnailSize.Medium),
VideoUri=await YouTube.GetVideoUriAsync("mhZdTqGsI14",YouTubeQuality.Quality360P)
},
new YouTubeVideo
{
YouTubeId="SrAD9qNi-8Q",
Title=await YouTube.GetVideoTitleAsync("SrAD9qNi-8Q"),
ThumbnailUri= YouTube.GetThumbnailUri("SrAD9qNi-8Q",YouTubeThumbnailSize.Medium),
VideoUri=await YouTube.GetVideoUriAsync("SrAD9qNi-8Q",YouTubeQuality.Quality360P)
},
new YouTubeVideo
{
YouTubeId="HOKfiXj75Ac",
Title=await YouTube.GetVideoTitleAsync("HOKfiXj75Ac"),
ThumbnailUri= YouTube.GetThumbnailUri("HOKfiXj75Ac",YouTubeThumbnailSize.Medium),
VideoUri=await YouTube.GetVideoUriAsync("HOKfiXj75Ac",YouTubeQuality.Quality360P)
},
};
return LstVideos;
}
private void LVVideos_ItemClick(object sender, ItemClickEventArgs e)
{
YouTubeVideo video = (YouTubeVideo)e.ClickedItem;
try
{
Player.Source = video.VideoUri.Uri;
TxtVideoName.Text = video.Title;
Player.Play();
}
catch (Exception)
{
// TODO show error (video uri not found)
}
}
In this code:
YouTubeId="SrAD9qNi-8Q",
Title=await YouTube.GetVideoTitleAsync("SrAD9qNi-8Q"),
ThumbnailUri= YouTube.GetThumbnailUri("SrAD9qNi-8Q",YouTubeThumbnailSize.Medium),
VideoUri=await YouTube.GetVideoUriAsync("SrAD9qNi-8Q",YouTubeQuality.Quality360P)
You can notice that the YouTube class has 3 useful methods:
· GetVideoTitleAsync() : Get the title of the YouTube video from the YouTubeId
· GetThumbnailUri() : Get the Thumbnail of the YouTube video from the YouTubeId
· GetVideoUriAsync() : Get the Uri of the YouTube video from the YouTubeId
In this code:
ProgressRingLoading.Visibility = Visibility.Collapsed;
GridContent.Visibility = Visibility.Visible;
We hide the ProgressRingLoading and display the GridContent once the data are loaded
Conclusion
In this article, we talked about how to play a YouTube video in Universal Windows application usingMyToolkit.Extended.
See Also
More information about MyToolkit for .NET
https://github.com/RSuter/MyToolkit
Download the project demo of this article
You can download all project in this link : https://gallery.technet.microsoft.com/Create-a-video-library-b0cc890f