Click here to Skip to main content
Click here to Skip to main content

Stream YouTube Videos in WPF

By , 30 Jun 2008
 

Introduction

This is going to be a quite small article, and probably not that useful, but I think it's quite cool all the same. Basically, this article shows how to play streaming videos from YouTube in WPF.

That's it.

So if this doesn't float your boat, I'd suggest stop reading right here.

This article also reads from an RSS feed... I know again, God you are always doing that, Sacha. Well, I promise I have other stuff; it's just that I like images and videos in WPF apps, and RSS feeds give you a nice diverse selection.

Prerequisites

This article relies on a piece of software being installed, which is: Microsoft .NET Framework 3.5 Service Pack 1 Beta.

This is required for the new WebBrowser control that comes with the SP1 installation.

OK, So What Does it Look Like

The app, when running, is yet another of my RSS feed search type apps. I promise this is the very last one of these. I just had to get this YouTube thing out of my system, so there you heard me say it: "no more RSS feed WPF articles!!!!!". Never. Never. I'm done with those.

Here are a couple of screenshots, assuming you clicked the Most Popular button:

You are free to drag the YouTube feed items around, providing you are currently in Drag mode, where the Mode is changeable using the right click context menu.

When you toggle out of Drag mode, you will be in Play mode, so will no longer be able to move the video items around. Instead, when you move the mouse over a video item, you will see a PLAY icon appear.

When you then click this PLAY icon, a new video viewer will be shown where you can view the YouTube video. This window is animated into/out of view. You should be able to open the viewer window whenever you are in Play mode and click on a unique video item.

That's all the screenshots, how does it all work?

How it Works

Well, starting at the top, the RSS feed ( ), this is actually just a bit of XLINQ, as follows:

public static List<YouTubeInfo> LoadVideosKey(string keyWord)
{
    try
    {
        var xraw = XElement.Load(string.Format(SEARCH,keyWord));
        var xroot = XElement.Parse(xraw.ToString());
        var links = (from item in xroot.Element("channel").Descendants("item")
                     select new YouTubeInfo
                     {
                         LinkUrl = item.Element("link").Value,
                         EmbedUrl = GetEmbedUrlFromLink(item.Element("link").Value),
                         ThumbNailUrl = GetThumbNailUrlFromLink(item),
                     }).Take(20);

        return links.ToList<YouTubeInfo>();
    }
    catch (Exception e)
    {
        Trace.WriteLine(e.Message, "ERROR");
    }
    return null;
}




// <summary>
/// Simple helper methods that tunrs a link string into a embed string
/// for a YouTube item. 
/// turns 
/// http://www.youtube.com/watch?v=hV6B7bGZ0_E
/// into
/// http://www.youtube.com/embed/hV6B7bGZ0_E
/// </summary>
private static string GetEmbedUrlFromLink(string link)
{
    try
    {
        string embedUrl = link.Substring(0, link.IndexOf("&")).Replace("watch?v=", "embed/");
        return embedUrl;
    }
    catch
    {
        return link;
    }
}


private static string GetThumbNailUrlFromLink(XElement element)
{

    XElement group = null;
    XElement thumbnail = null;
    string thumbnailUrl = @"../Images/logo.png";

    foreach (XElement desc in element.Descendants())
    {
        if (desc.Name.LocalName == "group")
        {
            group = desc;
            break;
        }
    }

    if (group != null)
    {
        foreach (XElement desc in group.Descendants())
        {
            if (desc.Name.LocalName == "thumbnail")
            {
                thumbnailUrl = desc.Attribute("url").Value.ToString();
                break;
            }
        }
    }

    return thumbnailUrl;
}

This is used within YouViewerMainWindow to create a bunch of YouTubeResultControl controls, which are then added to a DragCanvas. I can take no credit for the DragCanvas, I stole that straight from Josh Smith, using this code.

There is nothing special to say about the YouTubeResultControl controls; they are fairly simply controls, that simply contain a single YouTubeInfo item which is used within an event that is raised when the user clicks the internal YouTubeResultControl control's play button. YouViewerMainWindow uses the YouTubeInfo item to pass to the Viewer control, which in turn is responsible for playing the actual video.

So far nothing special, right? All very easy stuff.

The only part that's a bit interesting is that we can play the YouTube video in the new WebBrowser control. This is neat.

How does this work? Normally, WPF only lets you play Windows Media Player supported files that are local or MMS prefixed streams.

YouTube is neither of these, so how does it work? Well, luckily, the RSS feed contains enough information for us to do some string manipulation to get a new URL that points to something much more interesting.

Basically, from the RSS feed, we can get the following string: http://youtube.com/?v=FhZ-HsiS8aI. But if we mess around with it a bit, we can get: http://www.youtube.com/v/FhZ-HsiS8aI&hl=en, which is a link to a SWF (Flash) file that will play directly in the new browser if you paste this in to a browser address bar. Aha.

So we can use this new URL and use that as the Source property for the new .NET 3.5 SP1 WebBrowser control, and we get the usual YouTube player we are used to, for free. Neato. I also tried this with the .NET 2.0 WinForms WebBrowser (interop, so the WindowsIntegration DLL required) control, and the WPF Frame control, but they didn't work like the new .NET 3.5 SP1 WebBrowser control.

I had originally wanted to use the .NET 3.5 SP1 WebBrowser control, within my latest 3D WPF article MarsaX, but that didn't work on account of the fact that the new .NET 3.5 SP1 WebBrowser control is actually a HWnd based control, and really not much like a WPF control. So it doesn't play nice like other WPF controls, which is a shame, but it has led to this article.

And you know what? That's it.

As I say, this was a very quick and small article, so I don't expect too many votes for this one... But if you feel you want to vote, feel free, thanks.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Sacha Barber
Software Developer (Senior)
United Kingdom United Kingdom
Member
I currently hold the following qualifications (amongst others, I also studied Music Technology and Electronics, for my sins)
 
- MSc (Passed with distinctions), in Information Technology for E-Commerce
- BSc Hons (1st class) in Computer Science & Artificial Intelligence
 
Both of these at Sussex University UK.
 
Award(s)

I am lucky enough to have won a few awards for Zany Crazy code articles over the years

  • Microsoft C# MVP 2013
  • Codeproject MVP 2013
  • Microsoft C# MVP 2012
  • Codeproject MVP 2012
  • Microsoft C# MVP 2011
  • Codeproject MVP 2011
  • Microsoft C# MVP 2010
  • Codeproject MVP 2010
  • Microsoft C# MVP 2009
  • Codeproject MVP 2009
  • Microsoft C# MVP 2008
  • Codeproject MVP 2008
  • And numerous codeproject awards which you can see over at my blog

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionshow bar bottonmemberMember 955385029 Oct '12 - 13:26 
hi,
I tested the application and I liked a lot, but I can't see the bottom bar which you control the video time, volume, etc ...
Is it possible to display it?
 
Thank you.
QuestionPlay automaticallymemberMember 195943711 Oct '12 - 7:09 
Hi, I want to play the video automatically, it's this possible?
GeneralMy vote of 5memberbuddhika031812 Aug '12 - 8:23 
WOW Super
GeneralMy vote of 5memberMadhan Mohan Reddy27 Jun '12 - 20:55 
Super
GeneralMy vote of 5membersayooj cyriac22 May '12 - 21:45 
Thank you so much!!.. I have become a fan of your articles Smile | :)
Generalgreat !!memberyonop17 Jan '12 - 4:45 
Wonderfull - full!!
thanks !! Laugh | :laugh:
GeneralMy vote of 5memberseden seden16 Dec '11 - 21:04 
Thax for the articleSmile | :) Its amazing!
GeneralError :In the Populate funtionmemberbigaditya13 Mar '11 - 16:54 
When I run the code, in the populate function I get NUll exception.
Parameter Infos is null.
GeneralRe: Error :In the Populate funtionmvpSacha Barber5 Apr '11 - 5:28 
Should be ok now
Sacha Barber
  • Microsoft Visual C# MVP 2008-2011
  • Codeproject MVP 2008-2011
Open Source Projects
Cinch SL/WPF MVVM

Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

Generallocal viewer errormemberMegaGigsLtd4 Sep '10 - 14:59 
hello i am getting some error with the code
QuestionCreating a web chat facility in visual studio 2008 using Visual Basicmembershelle858 Apr '10 - 6:47 
I am creating a web chat facility in visual studio 2008 using Visual Basic,
I want to be able to highlight certain keywords that are sent and received to each user, can someone please tell me how I can do this? Thanks in advance

GeneralVB.NET vermemberBernard_Yanga5 Feb '10 - 7:15 
is there a VB.NET version of this tnx Smile | :)
GeneralRe: VB.NET vermvpSacha Barber5 Feb '10 - 20:58 
no, but there are plenty of online code converters
Sacha Barber
  • Microsoft Visual C# MVP 2008/2009
  • Codeproject MVP 2008/2009
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralWindows 7 problemmemberfanoo4 Aug '09 - 21:16 
When i ran you app in windows 7 build 7100 the app ask me to download the file.
GeneralRe: Windows 7 problemmvpSacha Barber4 Aug '09 - 21:46 
I dont have Windows 7 so cant test this, you will need to debug the code yourself. Have fun
 
Sacha Barber
  • Microsoft Visual C# MVP 2008/2009
  • Codeproject MVP 2008/2009
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralRe: Windows 7 problemmemberfanoo5 Aug '09 - 9:14 
No code to debug, it's an IE8 security warning when you paste
http://www.youtube.com/v/FhZ-HsiS8aI&hl=en
a message box that ask you if you want to download, open or cancel file. If you ask open no result... you need to revalidate url in the browser!
 
Do you know a solution to this issue ? or a work arround ?
 
Works fine in xp sp2 sp3, vista sp1 + ie7
GeneralRe: Windows 7 problemmvpSacha Barber5 Aug '09 - 9:34 
No work around Im afraid, see the next post down, they may have answer. Sorry
 
Sacha Barber
  • Microsoft Visual C# MVP 2008/2009
  • Codeproject MVP 2008/2009
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralRe: Windows 7 problemmemberfanoo22 Aug '09 - 2:08 
For 7 use NavigateToString and put in this string object and embed markup with swf url and no security warnigs apears.
Works fine now.
GeneralRe: Windows 7 problemmvpSacha Barber22 Aug '09 - 23:46 
Cool
 
Sacha Barber
  • Microsoft Visual C# MVP 2008/2009
  • Codeproject MVP 2008/2009
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralRe: Windows 7 problemmemberHunsoul2 Aug '10 - 6:38 
Could you clarify how to do it exactly?
GeneralRe: Windows 7 problemmemberyoavs5 Oct '10 - 14:28 
string path = (new Uri(videoUrl, UriKind.Absolute)).ToString();
                                   
                                    String template =
                                    @"&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;&lt;object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'
                                    codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0'
                                    width='400' height='320'&gt;
                                    &lt;param name='movie' value={0}.swf'&gt;           
                                    &lt;embed src='{0}.swf' width='400' height='320'  
                                    pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash'
                                    type='application/x-shockwave-flash'&gt;&lt;/embed&gt;&lt;/object&gt;&lt;/body&gt;&lt;/html&gt;";
 
                                    browser.NavigateToString(string.Format(template, path));
GeneralRe: Windows 7 problemmvpSacha Barber5 Apr '11 - 5:29 
I have now fixed this for Windows7 / new YouTube API
Sacha Barber
  • Microsoft Visual C# MVP 2008-2011
  • Codeproject MVP 2008-2011
Open Source Projects
Cinch SL/WPF MVVM

Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

Generalfile download security warningmemberMember 473915513 Jul '09 - 12:56 
when i click a video to play in this application i get a popup file download security warning with "Do you want to open or save this file?"
 
after i click on "run", the html page displayed reads "navigation to web page cancelled" with a link to refresh the page.
 
after click refresh then the youtube video is available, but you still have to click play.
 
i have the application set to full trust and the latest shock player download for IE.
 
Any suggestions very much appreciated.
GeneralRe: file download security warningmvpSacha Barber13 Jul '09 - 21:43 
Mmmmm the only thing I could think to try, is debug the code, see what Urls come back, copy one of them, and try that directly in browser, perhaps its a browser security thing.
 
Works for me though.
 
Sacha Barber
  • Microsoft Visual C# MVP 2008/2009
  • Codeproject MVP 2008/2009
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralRe: file download security warningmemberMember 473915515 Jul '09 - 6:33 
Thanks very much for your reply. I did paste the e.Info.EmbedUrl directly in IE 8 and it produces the security popup warning for Flash; Even though youTube listed as trusted site with min security in IE security settings.
 
Not sure if its a bug or something freaky with my system, but i have seen a few posts around the web with people having similar problem and contemplating jumping in front of a moving train after some time.
 
cheers!
GeneralRe: file download security warningmemberMember 473915515 Jul '09 - 6:53 
don't know if you are running IE8,but i found this. others having same issue.
 
http://www.eggheadcafe.com/conversation.aspx?messageid=34246456&threadid=34230179[^]
GeneralRe: file download security warningmvpSacha Barber15 Jul '09 - 10:05 
OK, actually I use Chrome.
 
Sacha Barber
  • Microsoft Visual C# MVP 2008/2009
  • Codeproject MVP 2008/2009
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralRe: file download security warningmemberMember 473915515 Jul '09 - 10:21 
sorry to be dense here, but i thought the web browser control was a wrapper around Internet Explorer and used the security settings from IE. If I could totally remove IE and still use the web browser control, that would be a good day.
GeneralRe: file download security warningmvpSacha Barber15 Jul '09 - 10:50 
No you are correct, I just thought you wanted to know browser I use, which is Chrome, but that WebBrowser control uses IE security I believe.
 
Sacha Barber
  • Microsoft Visual C# MVP 2008/2009
  • Codeproject MVP 2008/2009
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralRe: file download security warningmemberyoavs5 Oct '10 - 14:30 
string path = (new Uri(videoUrl, UriKind.Absolute)).ToString();
                                   
                                    String template =
                                    @"<html><head></head><body><object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'
                                    codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0'
                                    width='400' height='320'>
                                    <param name='movie' value={0}.swf'>           
                                    <embed src='{0}.swf' width='400' height='320'  
                                    pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash'
                                    type='application/x-shockwave-flash'></embed></object></body></html>";
 
                                    browser.NavigateToString(string.Format(template, path));
QuestionRenderTrasform on the WebBrowser containing the playermemberBLATEER14 Jun '09 - 7:01 
Thanks, it's simple and works well except when I apply a RotatTransform to the browser. the player never rotates with its container. is there another solution?? I need all transforms cause I'm designing a tabletop interface. the player can be rotated to any direction.
AnswerRe: RenderTrasform on the WebBrowser containing the playermvpSacha Barber14 Jun '09 - 21:36 
Yeah that wont work the WPF Browser control is a HWnd based control and is only just a wrapper around the winforms one, as such it does not respect WPF things like transforms.
 
It sucks but there you go.
 
Sacha Barber
  • Microsoft Visual C# MVP 2008/2009
  • Codeproject MVP 2008/2009
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralVista 64 IE7 problemmembermfmanca26 Feb '09 - 13:21 
When trying to use the Viewer alone in another xaml application, when I try to open a youtube video the webBrowser is asking to open/save the swf file...
What am I missing?
GeneralRe: Vista 64 IE7 problemmvpSacha Barber1 Mar '09 - 11:00 
mfmanca wrote:
What am I missing?

 
Nothing as far as I know, though I do not have the same Vista version, so could be something strange with that. I cant repeat it sorry.
 
Sacha Barber
  • Microsoft Visual C# MVP 2008/2009
  • Codeproject MVP 2008/2009
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

Generalstreaming videosmemberNicko Satria Utama16 Jan '09 - 5:03 
I think you use your own codecs and embed it into WPF mechanism so it can play directly the flv file Smile | :)
GeneralMerry ChristmasmemberAbhijit Jana24 Dec '08 - 3:11 
MERRY CHRISTMAS !!
 
------------------------------------------------------
Wishing A Merry Christmas to my GURU and his Family!!!
------------------------------------------------------
 
cheers,
Abhijit

GeneralRe: Merry ChristmasmvpSacha Barber24 Dec '08 - 5:55 
Ah thanks man, thats very nice.
 
You have a great one and all.
 
Sacha Barber
  • Microsoft Visual C# MVP 2008
  • Codeproject MVP 2008
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralThanks Sachamemberzues_bigglo23 Dec '08 - 5:52 
I have used a few of your articles and all I have to say is thanks so much for sharing your work to allow others to learn from it!
GeneralRe: Thanks SachamvpSacha Barber23 Dec '08 - 22:06 
Hey no worries glad even the king of gods (zues) can learn from me, thats pretty cool.
 
To be honest I am kinda hyper active and NEED TO DO stuff ALL the time, so articles help me focus my wandering attention span.
 
Sacha Barber
  • Microsoft Visual C# MVP 2008
  • Codeproject MVP 2008
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralPlay SWF in WPFmemberctrlnick14 Nov '08 - 9:25 
Hi Sacha,
Can you suggest me how to play swf files in WPF code?
 
Thanks
 
Happy Programming!
 
Regards,
ctrlnick !

GeneralRe: Play SWF in WPFmvpSacha Barber17 Nov '08 - 9:44 
Yeah use the Flash player active x hosted in a winformshost element.
 
use my blog post http://sachabarber.net/?p=149 to help you
 
Sacha Barber
  • Microsoft Visual C# MVP 2008
  • Codeproject MVP 2008
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

GeneralThe tag 'WebBrowser' does not exist in XML namespacememberdaveice15 Oct '08 - 22:40 
Could you tell me what's the problem..
 
I'm new bie, Smile | :)
GeneralRe: The tag 'WebBrowser' does not exist in XML namespacemvpSacha Barber16 Oct '08 - 3:02 
You need .NET 3.5 SP1.
 
Sacha Barber
  • Microsoft Visual C# MVP 2008
  • Codeproject MVP 2008
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

QuestionQuestion on this articlememberchico@dsi28 Sep '08 - 8:55 
Hello Sacha,
 
first of all let me congratulate you on the efforts you are making to show what WPF is all about.
Regarding this article, i liked it very much and i wanted to ask you something about the use of the
new webbrowser control.
How can we control the embedded object programmatically ?
I tryed to find the javascript function for playvideo on the page's DOM and invoke it with webbrowser.invokescript(..) without success. Would this be the right direction ?
 
Thank you,
Francisco
AnswerRe: Question on this articlemvpSacha Barber28 Sep '08 - 21:53 
Yeah this is the approach I have seen used with a Winforms web browser, there was an excellent demo which used google earth + WPF, have a search on google for it, it should be easy enough to find, but that shows how to interact with the browser very well.
 
Sacha Barber
  • Microsoft Visual C# MVP 2008
  • Codeproject MVP 2008
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

QuestionMine breaks....?memberjcovert18 Jul '08 - 6:05 
Hey. All seems well when I run, but when I try to play a video, I get an "Access Violation" exception of some kind. Do I need to download a flash player update or something?
AnswerRe: Mine breaks....?memberjcovert18 Jul '08 - 6:14 
Definitely should have tested out my *own* suggested solution before complaining. Turns out that because the web browser uses IE, and because I have never updated IE with the latest flash player (I use firefox, with flash updated properly), it was breaking. A quick update fixed it all. Thanks!
GeneralRe: Mine breaks....?mvpSacha Barber18 Jul '08 - 6:21 
cool
 
Sacha Barber
  • Microsoft Visual C# MVP 2008
  • Codeproject MVP 2008
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

JokeThis is awesome.memberDr.Luiji17 Jul '08 - 10:56 
Awesome article Sacha!
GeneralRe: This is awesome.mvpSacha Barber17 Jul '08 - 23:18 
Its very simple, but I think it works
 
Thanks
 
Sacha Barber
  • Microsoft Visual C# MVP 2008
  • Codeproject MVP 2008
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 30 Jun 2008
Article Copyright 2008 by Sacha Barber
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid