Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

How To Search And Show YouTube Videos in ASP.NET

With faster Internet connections, video sharing sites became very popular. Now almost every web site offers video content in addition to traditional text articles and images. There are two basic ways to show videos on ASP.NET web site:

1. Show videos hosted on some public sharing video site, like YouTube.

2. Host video files on your own server and play it using Flash, Windows Media, QuickTime or some other video player.

 

Second option gives you more control, but it also demands higher bandwidth costs and a lot of disc space on server. Most popular video format on Internet is .flv (Flash video) files, used by YouTube, Google videos and many other popular video sharing sites. To show Flash video file hosted on your server check How To Play Flash Video Files In ASP.NET tutorial. Other formats are not so popular on Internet but can be the best solution for intranet application. For example, to show different video formats in ASP.NET application you can use our free ASP.NET Media Player Control that automates work with Media Player and can show almost all possible video formats (although user must have Windows operating system because other OSs doesn't come with Media Player). In this tutorial, we'll research 1. option, how to search and show video files hosted on YouTube.

How to show YouTube video on ASP.NET page

Showing YouTube video on web page is simple. If you browse YouTube and watch some interesting video, notice Embed text box on the right side, like in image bellow:

Getting code to embed YouTube video

Click on small button with blue gear opens additional options like video size, player's colors, border etc. Code inside text box looks similar to this:

<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/5P6UU6m3cqk&hl=en_US&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/5P6UU6m3cqk&hl=en_US&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>

Now, to show this video on web page, you need only to copy this code and paste it on your page, which is good enough for static pages and small number of videos. Code includes several parameters to adopt it on different pages. Most important parameter is video ID (bolded in code above) used to specify which video you want to show. If we want to display other video, simply place its ID on appropriate place in code. To change it with ASP.NET server side code we can use simple Response.Write() method. On the same way, all other parameters could be changed to better fit in website design. Complete list of YouTube player parameters you can find on YouTube Embedded Player Parameters page.

How to get YouTube video thumbnail

To display thumbnail image of YouTube video, use this syntax:

http://img.youtube.com/vi/5P6UU6m3cqk/default.jpg

Bolded part is video ID, replace it to show any other video thumbnail. Default image has small size , to get larger thumbnail use this code:

http://img.youtube.com/vi/5P6UU6m3cqk/0.jpg

All thumbnails are listed in form of:

http://img.youtube.com/vi/5P6UU6m3cqk/default.jpg
http://img.youtube.com/vi/5P6UU6m3cqk/1.jpg
http://img.youtube.com/vi/5P6UU6m3cqk/2.jpg
http://img.youtube.com/vi/5P6UU6m3cqk/3.jpg

Then, instead of showing just one default image, you can improve user experience and show all thumbnails or even rotate images with Ajax or JavaScript.

How to get all information of YouTube video

To get all video information, use this syntax:

http://gdata.youtube.com/feeds/api/videos/5P6UU6m3cqk

Bolded part is video ID. This link will return all video data in different formats. Default format of feed is atom, other valid values are rss, json and json-in-script. Use alt parameter to change format, for example, to return video data in form of RSS feed set alt=rss, like this:

http://gdata.youtube.com/feeds/api/videos/5P6UU6m3cqk?alt=rss

Returned feed contains data like video title, description, categories, author, date published, rating, duration, keywords, statistics etc. You can load this feed into XPathDocument object and access items using XPath queries. Example code that finds video title and description could look like this:

[ C# ]

using System;
 
// We need System.Xml.XPath namespace to query XML
using System.Xml.XPath;
 
public partial class _Default : System.Web.UI.Page
{
 
 protected void Page_Load(object sender, EventArgs e)
 {
   // Load video information from YouTube
   XPathDocument videoInfo = new XPathDocument(
     "http://gdata.youtube.com/feeds/api/videos/5P6UU6m3cqk?alt=rss");
 
   // Create XPath navigator
   XPathNavigator videoInfoNavigator = videoInfo.CreateNavigator();
 
   // Gets YouTube video title
   string Title = videoInfoNavigator.SelectSingleNode("/item[1]/title").Value;
   // Gets YouTube video description
   string Description = videoInfoNavigator.SelectSingleNode("/item[1]/description").Value;
 
   // Write results
   Response.Write("Video title: " + Title + "<br />" +
     "Description: " + Description);
  }
}

[ VB.NET ]

Imports System
Imports System.Web
 
' We need System.Xml.XPath namespace to query XML
Imports System.Xml.XPath
 
Partial Class DefaultVBNET
 Inherits System.Web.UI.Page
 
 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
   ' Load video information from YouTube
   Dim videoInfo As XPathDocument = New XPathDocument( _
     "http://gdata.youtube.com/feeds/api/videos/5P6UU6m3cqk?alt=rss")
 
   ' Create XPath navigator
   Dim videoInfoNavigator As XPathNavigator = videoInfo.CreateNavigator()
 
   ' Gets YouTube video title
   Dim Title As String = videoInfoNavigator.SelectSingleNode("/item[1]/title").Value
   ' Gets YouTube video description
   Dim Description As String = videoInfoNavigator.SelectSingleNode("/item[1]/description").Value
 
   ' Output results
   Response.Write("Video title: " & Title & "<br />" & _
     "Description: " & Description)
 End Sub
End Class

Show videos in DataList or some other data control

Now you can create YouTube video gallery. In DataList, GridView or some other data control create one template column. In ItemTemplate add code for YouTube player, but with changeable video ID. You can store video IDs in database like Sql Server and load it into SqlDataSource control, or get it directly from YouTube every time using YouTube API and store results into XmlDataSource.

In general, there are two options to organize and show videos, depending of your preferences you can:

- Show only video thumbnails in DataList with hyperlinks to another Player page where user can watch the video or
- Show YouTube video players directly in DataList

If you decide to show YouTube players in DataList be sure that autoplay parameter is 0. Default value is already zero, just don't change it if you have many players on page. Playing all movies with sounds in the same time would make confusion to most users, although some rare visitor would enjoy it :).

Using YouTube API to search videos

In the past, you needed to register and obtain developer key to use YouTube API. Now you can search videos as anonymous, all data reading is not restricted. Developer key is needed only for things like upload your videos to YouTube programmatically. For example, let say I want to search for Age of Empires videos (AoE is popular strategic game). Simple syntax would be:

http://gdata.youtube.com/feeds/api/videos?q=age+of+empires&prettyprint=true&alt=rss

YouTube service will return XML with search results. To analyze this XML easier, I added prettyprint= true in request. This option format XML output nicely with line breaks and tabs. Complete list of available parameters you can find on http://code.google.com/apis/youtube/2.0/reference.html#Searching_for_videos page. Default XML format is atom, but in this example we'll use alt=rss to get output formatted as RSS feed.

My YouTube Search form will contain one TextBox control named tbSearch, one Button control named btnSearch and GridView to show search results. RSS returned from YouTube API has not structure acceptable for GridView. Because of that, I will use XmlDataSource control to load RSS and additional XSLT file to convert XML to format acceptable for GridView.

Code of XSLT file (named YouTube-Transform.xslt) that converts YouTube XML to XML for GridView control would be:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:msxsl="urn:schemas-microsoft-com:xslt"
 xmlns:media='http://search.yahoo.com/mrss/'
 xmlns:yt='http://gdata.youtube.com/schemas/2007'
 exclude-result-prefixes="msxsl">
 <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
 <xsl:template match="/">
  <xsl:element name="items">
   <xsl:for-each select="/rss/channel/item">
    <xsl:element name="item">
     <xsl:attribute name="title">
      <xsl:value-of select="title"/>
     </xsl:attribute>
     <xsl:attribute name="description">
      <xsl:value-of select="media:group/media:description" />
     </xsl:attribute>
     <xsl:attribute name="author">
      <xsl:value-of select="author" />
     </xsl:attribute>
     <xsl:attribute name="keywords" >
      <xsl:value-of select="media:group/media:keywords" />
     </xsl:attribute>
     <xsl:attribute name="videoId" >
      <xsl:value-of select="media:group/yt:videoid"/>
     </xsl:attribute>
     <xsl:attribute name="duration" >
      <xsl:value-of select="media:group/yt:duration/@seconds"/>
     </xsl:attribute>
    </xsl:element>
   </xsl:for-each>
  </xsl:element>
 </xsl:template>
</xsl:stylesheet>

User will type search terms in TextBox and click Search button. I will use XmlDataSource control to bind returned data to GridView. GridView will show search results in one template column. ASP.NET markup code would be like this:

<asp:TextBox runat="server" ID="tbSearch" />
<asp:Button Text="Search" runat="server" ID="btnSearch" onclick="btnSearch_Click" /><br /><br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EnableViewState="false">
<Columns>
 <asp:TemplateField>
 <ItemTemplate>
 <table width="550"><tr>
 <td valign="top">
 <a href='https://beansoftware.com/ASP.NET-YouTube-Player.aspx?id=<%# Eval("videoId") %>'>
 <img border='0' src='http://img.youtube.com/vi/<%# Eval("videoId") %>/1.jpg' /><br /><br />
 <img border='0' src='http://img.youtube.com/vi/<%# Eval("videoId") %>/2.jpg' /><br /><br />
 <img border='0' src='http://img.youtube.com/vi/<%# Eval("videoId") %>/3.jpg' />
 </a>
 </td>
 <td valign="top">
 <h1><a href='https://beansoftware.com/ASP.NET-YouTube-Player.aspx?id=<%# Eval("videoId") %>'><%# Eval("title") %></a></h1><br />
 <p><b>Description:</b><%# Eval("description") %></p>
 <p><b>Author:</b> <%# Eval("author") %><br />
 <b>Keywords:</b> <%# Eval("keywords") %><br />
 <b>Duration:</b> <%# Eval("duration") %> seconds</p>
 </td>
 </tr></table>  
 </ItemTemplate>
 </asp:TemplateField>
</Columns>
</asp:GridView>
 
<asp:XmlDataSource ID="XmlDataSource1" runat="server" TransformFile="YouTube-Transform.xslt">
</asp:XmlDataSource>

On search button click, RSS will be loaded from YouTube, converted by XSLT and finally shown in GridView:

[ C# ]

protected void btnSearch_Click(object sender, EventArgs e)
{
 XmlDataSource1.DataFile = "http://gdata.youtube.com/feeds/api/videos?v=2&q=" +
   Server.UrlEncode(tbSearch.Text) + "&alt=rss";
 GridView1.DataSourceID = XmlDataSource1.ID;
}

[ VB.NET ]

Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
 XmlDataSource1.DataFile = "http://gdata.youtube.com/feeds/api/videos?v=2&q=" & _
   Server.UrlEncode(tbSearch.Text) & "&alt=rss"
 GridView1.DataSourceID = XmlDataSource1.ID
End Sub

By default, YouTube API returns first 25 records. You can change that using max-results parameter (max value is 50). To see other videos increase start-index parameter which is 0 by default. For example, if your page size is 20 records and you want to show third page, set start-index = 41 and max-results = 20.

Notice that query returns only one page per request, to show correct page every time you need to set XmlDataSource1.EnableCaching to False. Since data source contains only one page, you can't use default GridView paging. You can implement custom paging in GridView or use SEO Pager to resolve this issue. To find number of pages you can use syntax like NumberOfPages = Math.Ceiling(TotalResults / PageSize). Page size depends of max-results parameter used while total results value you can find in returned XML feed using XPath rss/channel/openSearch:totalResults.

Conclusion

Since YouTube uses Flash technology to show videos, web site visitors must have Flash player installed. Fortunately, Flash is widely used (at last, that is the reason why all main video sharing websites chosen Flash technology). Notice that some videos could be removed, marked as private, disabled for embedding or disabled for some client's locations.

Happy coding!


Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |   Google