YouTube class
YouTube.Play will download the YouTube page of the required YouTube-ID, search for the appropriate MP4-link and then play the video with the
MediaPlayerLauncher. It's a better method than using the
WebBrowserTask and browse to a YouTube-URL (eg "vnd.youtube:YOUTUBEID?vndapp=youtube_mobile")
The simplest call is
YouTube.Play("youtubeid"). This does not need any changes in the page code. To deactivate the current page until the MP4-link has been found, use
YouTube.Play("youtubeid", false).
There are two problems with the previous method. First it does not allow the user to cancel the download of the MP4 link (you have to extend the page's
OnBackKeyPress method). The second problem is that after downloading the video MP4 link you will notice that the page will be active until the MediaPlayerLauncher has started. To solve both problems use
YouTube.Play("youtubeid", true) and add the following code in
OnNavigatedTo and
OnBackKeyPress. This is the best but most "complex" solution:
public partial class MyPage : PhoneApplicationPage
{
protected override void OnBackKeyPress(CancelEventArgs e)
{
if (YouTube.CancelPlay()) // used to abort current youtube download
e.Cancel = true;
else
{
// your code here
}
base.OnBackKeyPress(e);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
YouTube.CancelPlay(); // used to reenable page
// your code here
base.OnNavigatedTo(e);
}
private void OnButtonClick(object o, RoutedEventArg e)
{
YouTube.Play("youtube_id", true, YouTubeQuality.Quality480P, (e) => { if (x != null) { MessageBox.Show(x.Message); } });
}
}
Eventually you should show the progress bar while downloading the MP4 link:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
YouTube.CancelPlay(); // used to reenable page
SystemTray.ProgressIndicator.IsVisible = false;
// your code here
base.OnNavigatedTo(e);
}
private void OnButtonClick(object o, RoutedEventArg e)
{
SystemTray.ProgressIndicator.IsVisible = true;
YouTube.Play("youtube_id", true, YouTubeQuality.Quality480P, x =>
{
if (x != null)
MessageBox.Show(x.Message);
});
}
}
WinRT and MediaElement
To play a YouTube video in WinRT MediaElement, use the GetVideoUriAsync:
var url = await YouTube.GetVideoUriAsync(youTubeId, YouTubeQuality.Quality1080P);
var player = new MediaElement();
player.Source = url.Uri;
Classes