Introduction
This extended version of embedded YouTube™ API demonstrates additional customization features, namely:
- Setting the startup options
- Selecting the item from the playlist
- Setting the autoplay mode
- Setting player's dimension (W/H)
- Changing the border options
- Starting the video at predefined time
This project extends the functionality of embedded YouTube Video Player API described in my previous article [1]
Start-up mode
Start-up options could be set by using Web Query; as an example, the following query sets the autoplay option and selected item index=2 (see the sample screenshot taken from the functional demo here). Also, the start-up time for each item could be set programmatically. Notice two command buttons at the bottom of the sample screenshot in Figure 1; clicking on these buttons when the actual application is running will cause the playback to start at a certain predefined position (15 sec and 60 sec correspondingly).
Figure 1: Embedded YouTube™ player with item start-up time set programmatically
Note: all images are included for Demo purpose only. Please do not copy/redistribute.
Using the Code
Project includes:
- Default Web page "Default.aspx" with corresponding code behind: both to be placed in Application root directory
- Class module YouTubeScript.cs to be placed in App_Code application folder
Sample Web Page includes a Literal1
control, serving as a JavaScript container and a populated DropDownList
control with two sample items, serving as a simple playlist:
<%@ Page Language="C#"
AutoEventWireup="true"
CodeFile="Default.aspx.cs"
Inherits="_DEMO" %>
<!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>ASP.NET Embedded Video Player | YouTube DEMO</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="x_4CNvG1Q_M">
Anastasia Volochkova dancing (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>
<asp:Button ID="Button1" runat="server"
Text="START AT 15 SEC" onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server"
Text="START AT 60 SEC" onclick="Button2_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<hr />
<h4>Sample Demo: Anastasia Volochkova,
Russian prima ballerina is dancing "Adiemus"</h4>
<h4>Initial settings: 640x505, autoplay=0</h4>
<hr />
More Demo available at: www.webinfocentral.com
<hr />
</form>
</body>
</html>
Code Behind Page
using System;
public partial class _DEMO : System.Web.UI.Page
{
#region init settings
private int _W = 640;
private int _H = 505;
bool auto = false;
#endregion
#region Page Load event
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
#region Start mode customization via Web Query String
int idx = 0;
string qry = "";
try {
qry = "auto";
qry = (Request.QueryString[qry] == null) ?
"" : Request.QueryString[qry];
if (qry != "") { auto = Boolean.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, false, _W, _H);
}
}
#endregion
#region User events
protected void Button1_Click(object sender, EventArgs e)
{
Literal1.Text =
YouTubeScript.Get(cmbPlaylist.SelectedValue, true,
_W, _H, true, "maroon", "", 15);
}
protected void Button2_Click(object sender, EventArgs e)
{
Literal1.Text =
YouTubeScript.Get(cmbPlaylist.SelectedValue, true,
_W, _H, false, "", "", 60);
}
#endregion
}
Note: try
-catch
blocks in Page_Load
event procedure are inserted for future development. Also, as mentioned in comments, int.Parse can be replaced with int.TryParse(), the same goes to Boolean parsing, eliminating the need for particular try-catch blocks.
Class Module
using System;
using System.Text;
public static class YouTubeScript
{
private const int _defaultW= 320;
private const int _defaultH = 240;
#region YouTube Player default script: no autoplay, 320x240
public static string Get(string id)
{ return Get(id, false, _defaultW, _defaultH); }
#endregion
#region YouTube Player script w/autoplay option (320x240)
public static string Get(string id, bool auto)
{ return Get(id, auto, _defaultW, _defaultH ); }
#endregion
#region YouTube Player script w/autoplay option (320x240)
public static string Get(string id, int auto)
{ return Get(id, ((auto == 1) ? true : false), _defaultW, _defaultH ); }
#endregion
#region YouTube Player script w/selectable: autoplay and W/H
public static string Get(string id, bool auto, int W, int H)
{ return Get(id, auto, W, H, true); }
#endregion
#region YouTube Player script w/selectable: autoplay, W/H and default border
public static string Get(string id, bool auto, int W, int H, bool Border)
{ return Get(id, auto, W, H, Border, "0x2b405b", "0x6b8ab6",0 ); }
#endregion
#region YouTube Player script w/selectable: autoplay, W/H and border color
public static string Get
(string id,
bool auto,
int W,
int H,
string C1,
string C2)
{ return Get(id, auto, W, H, true, C1,C2, 0); }
#endregion
#region YouTube Player script w/selectable: autoplay, W/H and border color
public static string Get
(string id,
bool auto,
int W,
int H,
bool Border,
string C1,
string C2,
int Start)
{
StringBuilder sb = new StringBuilder();
sb.Append(@"<embed src='http://www.youtube.com/v/");
sb.Append(id);
if (auto) sb.Append("&autoplay=1");
sb.Append("&rel=0");
if (Border)
{
sb.Append("&border=1");
sb.Append("&color1=" + @C1);
sb.Append("&color2=" + @C2);
}
if (Start>0) sb.Append("&start=" + Start.ToString());
sb.Append("&fs=1");
sb.Append("' ");
sb.Append("type='application/x-shockwave-flash' ");
sb.Append("id='youTubePlayer" + DateTime.Now.Millisecond.ToString() + "' ");
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();
sb = null;
return scr;
}
#endregion
}
Note: marginal performance improvements can be achieved by using String.Concat() instead of Append() methods (used in the above code snippet for clarity and didactic purpose).
Browser compatibility
This technique has been tested against 4 major browsers:
- Microsoft Internet Explorer 7.0+
- Mozilla Firefox
- Google Chrome
- Apple Safari
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:
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
)
Demo
This demo screenshot demonstrates the technique described above using GridView control's custom Template field. Click on the image-link below to open fully-functional WebTV app [2]:
Fig2. WebTV pilot project powered by embedded YouTube API for ASP.NET, sample screenshot
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 [3]. Other controls provide additional navigation convenience (as in typical video player). The actual WebTV project also implements a scheduler that allows the items auto-progressing operational mode.
Note: all images are included for Demo purpose only. Please do not copy/redistribute.
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 (Views [6]). Currently 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 cumulative articles/tips views count in a range of 3 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). Play list could be also customized by music genre, e.g. Classical music [7], etc.
Points of Interest
YouTube playback customization technique
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
- Article was published on 09/15/2009
- Updated on 04/14/2013 w/more customization options
- Updated on 07/12/2015 describing WebTV w/enhanced set of controls
References
- YouTube™ API for ASP.NET
- Click/Select row in ASP.NET GridView or HTML 5 Table
- Hyperlinked Images in ASP.NET GridView
- Nested GridView controls in ASP.NET: best practices