This article demonstrates how to add YouTube Video Player to ASP.NET web pages using an API written in C# and a Microsoft AJAX extension, allowing for customization of dimensions, border options, autoplay settings, and more.
Fig. 1. Sample screenshot
Note: All images are included for demo purposes only. Please do not copy/redistribute.
Introduction
Embedded Video Players, based either on Adobe Flash™, Microsoft Silverlight™ or pure HTML5 video technology can dramatically enhance web page aesthetics and overall user experience. This article demonstrates the coding technique for embedding the rather popular YouTube™ Video Player (which is built on the aforementioned Adobe Flash™) in ASP.NET web pages via an API written in C# and a Microsoft AJAX extension.
The project contains:
- The default web page Default.aspx with the corresponding code-behind: both to be placed in the Application root directory (ASP.NET 2.0+).
- Code module YouTubeScriptGenerator.cs to be placed in the App_Code directory.
- AJAX library file (AjaxControlToolkit.dll) to be placed in the Bin directory
Background
The Embedded Video Player is capable of streaming (playing back) the audio/video content, available from the www.youtube.com website (Note: Subscription is not required in order to use this feature). The video item ID is encoded into a query string, looking like a random set of characters, for example: x_4CNvG1Q_M
, with corresponding full address string: http://www.youtube.com/watch?v=x_4CNvG1Q_M (in particular sample presumably pointing to the video clip titled: “Anastasia Volochkova dancing to Adiemus by Karl Jenkins).
The easiest way to embed the YouTube™ Video Player is to go to the www.youtube.com website, select the item of interest, and then copy/paste the corresponding snippet, located in the text box marked “embed”, into your own web page, and Voila! YouTube™ site provides several customization options regarding the video player size (this includes standard settings specified as: 340x285, 445x364, 500x405, 660x525) and color palette selection. The ASP.NET YouTube™ API described in this article provides a much wider set of customization features.
Using the Code
The practical steps to embed the YouTube™ Video Player into an ASP.NET Web Page are as follows:
- Create or open an ASP.NET Web Site using either Microsoft Visual Studio (any edition) or the Visual Web Developer Express edition.
- Download the compressed (.zip) file. Extract the components into your web application directory.
- Set the embedded YouTube™ Video Player dimension: W/H.
- Customize the YouTube™ Video Player border options.
- Customize the YouTube™ Video Player startup settings:
- First item to play
- Autoplay mode
- Starting the Video/Audio streaming at a predefined time.
Following are the code snippets corresponding to the demo ASPX web page with the associated code-behind module:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="default_aspx" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>YouTube ASP.NET Sample</title>
<meta name="Description" content="YouTube Player API for ASP.NET, Demo" />
<meta name="Keywords" content="youtube, video, player, asp.net, javascript," />
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta http-equiv="Author" content="Alexander Bell" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Cache-control" content="no-cache" />
</head>
<body>
<form id="form1" runat="server">
<h3>ASP.NET Embedded Player: Demo</h3>
<p>Initial settings: 640x480, autoplay=0</p>
<br />
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" updatemode="Conditional" >
<ContentTemplate>
<div>
<asp:DropDownList ID="cmbPlaylist" runat="server" AutoPostBack="True">
<asp:ListItem Value="UelDrZ1aFeY">The Beatles - Something</asp:ListItem>
<asp:ListItem Value="xFrGuyw1V8s">Abba - Dancing Queen</asp:ListItem>
<asp:ListItem Value="A_MjCqQoLLA">The Beatles - Hey Jude</asp:ListItem>
<asp:ListItem Value="djV11Xbc914">a-ha - Take On Me</asp:ListItem>
<asp:ListItem Value="1lyu1KKwC74">The Verve - Bitter Sweet Symphony</asp:ListItem>
<asp:ListItem Value="nVhNCTH8pDs">Pink Floyd - Learning To Fly</asp:ListItem>
</asp:DropDownList>
<br /><br />
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<h4>NOTE: ALL CONTENT IS SHOWN FOR DEMO PURPOSE ONLY</h4>
</form>
</body>
</html>
The code-behind:
using System;
using System.Text;
public partial class default_aspx : System.Web.UI.Page
{
private int _W = 640;
private int _H = 480;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
#region Start mode customization via Web Query String
const string AUTO = "auto";
const string IDX = "idx";
int idx = 0;
int auto = 0;
try {
string _auto = Request.QueryString[AUTO] ?? String.Empty ;
if (_auto != String.Empty) auto = int.Parse(_auto);
string _idx= Request.QueryString[IDX] ?? String.Empty;
if (_idx != String.Empty) idx = int.Parse(_idx);
}
catch { }
#endregion
cmbPlaylist.SelectedIndex = idx;
Literal1.Text = Get(cmbPlaylist.SelectedValue, auto, _W, _H);
}
else
{
Literal1.Text = Get(cmbPlaylist.SelectedValue, 0, _W, _H);
}
}
#region YouTube script to set: item, autoplay option, screen W/H
private string Get(string id, int auto, int W, int H)
{
StringBuilder sb = new StringBuilder();
sb.Append(@"<embed src='http://www.youtube.com/v/");
sb.Append(id);
sb.Append("&autoplay=");
sb.Append(auto.ToString());
sb.Append("' ");
sb.Append("type='application/x-shockwave-flash' ");
sb.Append("allowscriptaccess='never' enableJavascript ='false' ");
sb.Append("allowfullscreen='true' ");
sb.Append("width='" + W.ToString() + "' ");
sb.Append("height='" + H.ToString() + "' ");
sb.Append(@"></embed>");
string scr = sb.ToString();
return scr;
}
#endregion
}
WebTV Project
The section described powerful video streaming technology based on YouTube player embedded in ASP.NET web page. What's next? The logical extension would be adding a playlist controls and bind it to the underlying database. ASP.NET GridView
control can perfectly fit the purpose: it allows creation of the templated field with advanced CSS styling [4,5] (other option would be implementing full-fledged MVC, but for such relatively simple task it seems an overkill). The possible implementation is shown below in the sample screenshot.
Backend Database
The backend database could be of any type. Its main Table should contain a mandatory VideoID
field (unique key), which identifies the video item on YouTube (it's used as a web query parameter, for example: VidID=9bZkp7q19f0
corresponds to the most popular music-video of all time "Gangnam Style" by PSY). The other fields are optional, like: Title, Performer, Views, Likes, Duration, etc., so the generic video items Table creation schema may look like the following snippet:
Table 1. Video Items master table
CREATE TABLE VideoItems
(
ID int NOT NULL PRIMARY KEY,
VidID varchar(20) NOT NULL UNIQUE,
Title nvarchar(255) NOT NULL,
Performer nvarchar(255),
Duration int,
Views long,
Likes long,
Dislikes long
)
Adding Features to WebTV
The backend database linked to the Youtube Video Player provides plenty of room for further customization/extension. The first quite obvious 'data mining' extension would be sorting the items based on their popularity. Currently (as of the year 2015) 2 YouTube 'GigaMen' identified (Justin Bieber and PSY) having 1+ billion views per a single video item, and one 'GigaLady' (Katy Perry) has been added to the said YouTube Giga-club. This astronomical popularity of music-video genre is sort of mind-boggling, indeed! With kind of bitter irony, my 4+ million CodeProject articles/tips cumulative views count put me in a category of just entry-level cat videos (so far, the most popular "Nyan Cat" video accounts for approx. 122 mega-views).
Playlist could be also customized by music genre, for example, Classical music, etc., thus creating the video channels under topical umbrella as discussed in the following sub-chapter.
Adding Channels
Possible further extension of this video-streaming technology would be creating channels by adding two more Tables to the backend DB, in addition to master table of VideoItems described above:
Table 2. Video Channels
CREATE TABLE VideoChannels
(
CID int NOT NULL PRIMARY KEY,
Channel varchar(50) NOT NULL UNIQUE,
Description nvarchar(255)
)
Table 3. Video Channels-Items join table
CREATE TABLE ChannelItems
(
CVID int NOT NULL PRIMARY KEY,
VidID varchar(20) NOT NULL,
CID int NOT NULL,
Position int NOT NULL,
Comments nvarchar(255),
)
where VidID
and CID
and Foreign Keys linking the table to the master VideoItems
and Channels
tables, correspondingly. Also, Unique
constraint could be added to composite (VidID
, CID
) index in order to avoid duplicate video items appear in the same channel. Position
field specifies where the item should appear in the playlist (channel), so the corresponding SQL Select statement must include the ORDER BY [Position]
clause.
As mentioned above, content of the channels can be dynamically updated on time basis (daily, weekly, monthly, etc.).
Demo
This demo screenshot demonstrates the technique described above using GridView
control's custom Template field.
Top-100 Summertime Music Videos online channel, sample screenshots
WebTV app w/daily scheduler, sample screenshots
Note: All images are included for demo purpose only. Please do not copy/redistribute.
In screenshot images shown above, the section to the left contains embedded YouTube player: section to the right is made of GridView
control linked to the app backend database with functionality extended via JavaScript. Other controls provide additional navigation convenience (as in typical video player).
Points of Interest
Smooth transition between video items is achieved by using the Microsoft AJAX extension: notice the UpdatePanel
where resides the Literal1
control containing the corresponding JavaScript.
YouTube Video Playback Customization
Other points of interest may include a video playback customization, related to the linked (not embedded) YouTube video items. This customization technique allows to:
- Start video playback at specific position (set offset in minutes and second)
- Specify the number of video re-plays (Loop)
- Start the video playback in Full Screen Mode
- Turn “Related Video” options ON/OFF
- Set the Autoplay options
- Set the Playback Video Quality
History
- 1st August, 2014: Updated with more customization options and YouTube stats
- 30th April, 2013: Time to switch to jQuery 2.0 (done)
- 30th April, 2013: Made this player HTML5-compatible (key changes:
<iframe class='youtube-player' type='text/html' frameborder='0' id="player"></iframe>
and the rest in jQuery derived from this). - 20th July, 2015: The concept and implementation of WebTV Channels technical discussion has been added.
References
- YouTube™ Embedded Video Player: Extended API (C#)
- Click/select row in ASP.NET GridView or HTML table
- Nested GridView controls in ASP.NET: best practices
- Hyperlinked Images in ASP.NET GridView
- Bottle.IsNullOrEmpty(), Lounge Discussion