
Fig. 1. Sample screenshot
Note: all images are included for Demo purpose 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"
CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Register assembly="AjaxControlToolkit"
namespace="AjaxControlToolkit"
tagprefix="cc1" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>DEMO | YouTube API for ASP.NET</title>
</head>
<body>
<form id="form1" runat="server">
<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="XP9tzWtLFus">Anastasia
Volochkova(Adiemus)</asp:ListItem>
<asp:ListItem Value="raRaxt_KM9Q">Sound Of Silence
(Masters of Chant)</asp:ListItem>
</asp:DropDownList>
<br /><br />
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<hr />
<h3>Sample Demo: Anastasia Volochkova, Russian prima ballerina
dancing "Adiemus"</h3>
<h4>Initial settings: 640x480, autoplay=0</h4>
<hr />
<h4>
More Demo available at: <a href="www.webinfocentral.com"
target="_blank">www.webinfocentral.com</a>
</h4>
<hr />
</form>
</body>
</html>
The code-behind:
using System;
public partial class _Default : 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
int idx = 0;
int auto = 0;
string qry = "";
try {
qry = "auto";
qry = (Request.QueryString[qry] == null) ? "" : Request.QueryString[qry];
if (qry != "") { auto = int.Parse(qry); }
} catch { }
try {
qry = "item";
qry = (Request.QueryString[qry] == null) ? "" : Request.QueryString[qry];
if (qry != "") { idx = int.Parse(qry); }
} catch { }
#endregion
cmbPlaylist.SelectedIndex = idx;
Literal1.Text = YouTubeScript.Get(cmbPlaylist.SelectedValue, auto, _W, _H);
}
else
{
Literal1.Text = YouTubeScript.Get(cmbPlaylist.SelectedValue, 0, _W, _H);
}
}
}
WebTV Project
The section above 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 bing 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-fleged MVC, but for such relatively simple task it seems an overkill). The possible implementation is shown below in 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
Hide Copy Code
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 (note: corresponding to the year 2015) their are 2 'Gigamen' (Justing Bieber and PSY) with more that 1 billion views per a single video item and one recently added to the giga-club 'GigaLady' (Katy Perry). Most likely Taylor Swift will join the "Giga-club" some time soon (stay tune). A word to add: this astronomical popularity of music-video genre is sort of mind-boggling! With a sort of bitter irony, my Codeproject articles/tips cumulative views count in the range of 4 million 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, e.g. 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. These 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 option
- Set the Playback Video Quality
History
- Updated with more customization options and YouTube stats on 08/01/2014
- 04/30/2013 Time to switch to jQuery 2.0 (done)
- 04/30/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).
- 7/20/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