Click here to Skip to main content
11,483,002 members (70,589 online)
Click here to Skip to main content

YouTube™ Embedded Video Player: Extended API (C#)

, 24 Feb 2015 Ms-PL 147.2K 98
Rate this:
Please Sign up or sign in to vote.
YouTube™ video player API provides variety of customization features (ASP.NET, C#)

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

Background

This project extends the functionality of embedded YouTube Video Player API described in my previous article, published here (see the sample screenshot in Figure 1 related to the previous project).

Figure 1: Embedded YouTube™ Video Player, sample screenshot

You could also see the functional demo of Data-Bound YouTube™ API here.

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 2; 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 2: Embedded YouTube™ player with item start-up time set programmatically

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>
                    <!-- ALL CONTENT IS SHOWN FOR DEMO PURPOSE ONLY-->
                    <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

//****************************************************************************
// Module           :   Default.aspx.cs
// Type             :   ASP.NET web page code behind
// Developer        :   Alexander Bell (Infosoft International Inc)
// Description      :   YouTube API for ASP.NET (DEMO)
//****************************************************************************
// DISCLAIMER: This Application is provide on AS IS basis without any warranty
//****************************************************************************

//****************************************************************************
// TERMS OF USE     :   ALL CONTENT IS SHOWN FOR DEMO PURPOSE ONLY
//****************************************************************************
using System;

public partial class _DEMO : System.Web.UI.Page
{
    #region init settings
    // player width
    private int _W = 640;

    // player height
    private int _H = 505;

    // autoplay disabled
    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 = "";

            // Web Query to set autoplay option
            try {
                qry = "auto";
                qry = (Request.QueryString[qry] == null) ? 
				"" : Request.QueryString[qry];
                if (qry != "") { auto = Boolean.Parse(qry); }
            } catch { }

            // Web Query to set item index
            try {
                qry = "item";
                qry = (Request.QueryString[qry] == null) ? 
				"" : Request.QueryString[qry];
                if (qry != "") { idx = int.Parse(qry); }
            } catch { }
            #endregion

            // set selected index
            cmbPlaylist.SelectedIndex = idx;

            // generate script on page load
            Literal1.Text = YouTubeScript.Get(cmbPlaylist.SelectedValue, auto, _W, _H);
        }
        else
        {
            // generate script on page postback
            Literal1.Text = YouTubeScript.Get(cmbPlaylist.SelectedValue, false, _W, _H);
        }
    }
    #endregion

    #region User events
    /// <summary>
    /// Script to start video at predefined time, change border color
    /// </summary>
    protected void Button1_Click(object sender, EventArgs e)
    {
       // set start time = 15 sec, change border colors
        Literal1.Text =
        YouTubeScript.Get(cmbPlaylist.SelectedValue, true,
        _W, _H, true, "maroon", "", 15);
    }

    /// <summary>
    /// Script to start video at predefined time, remove border
    /// </summary>
    protected void Button2_Click(object sender, EventArgs e)
    {
        // set start time = 60 sec, remove border
        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

//******************************************************************************
// Module           :   YouTubeScript.cs
// Author           :   Alexander Bell
// Copyright        :   2009 Infosoft International Inc
// Description      :   YouTube Player Javascript generator

//******************************************************************************
// DISCLAIMER: This Application is provide on AS IS basis without any warranty
//******************************************************************************

//******************************************************************************
// TERMS OF USE     :   This module is copyrighted.
//                  :   You can use it at your sole risk provided that you keep
//                  :   the original copyright note.
//******************************************************************************

using System;
using System.Text;

///*****************************************************************************
/// <summary>
/// Generate Javascript to embed YouTube Video Player in ASP.NET web page
/// </summary>
public static class YouTubeScript
{
    private const int _defaultW= 320;
    private const int _defaultH = 240;

    #region YouTube Player default script: no autoplay, 320x240
    /// <summary>
    /// YouTube Player default script: no autoplay, 320x240
    /// </summary>
    /// <param name="id">id</param>
    /// <param name="auto">int</param>
    /// <returns>string</returns>
    public static string Get(string id)
    { return Get(id, false, _defaultW, _defaultH); }
    #endregion

    #region YouTube Player script w/autoplay option (320x240)
    /// <summary>
    /// YouTube Player script w/autoplay option (320x240)
    /// </summary>
    /// <param name="id">id</param>
    /// <param name="auto">bool</param>
    /// <returns>string</returns>
    public static string Get(string id, bool auto)
    { return Get(id, auto, _defaultW, _defaultH ); }
    #endregion

    #region YouTube Player script w/autoplay option (320x240)
    /// <summary>
    /// YouTube Player script w/autoplay option (320x240)
    /// </summary>
    /// <param name="id">id</param>
    /// <param name="auto">int</param>
    /// <returns>string</returns>
    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
    /// <summary>
    /// YouTube Player script w/selectable: autoplay and W/H options
    /// </summary>
    /// <param name="id">id</param>
    /// <param name="auto">bool</param>
    /// <param name="W">int</param>
    /// <param name="H">int</param>
    /// <returns>string</returns>
    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
    /// <summary>
    /// YouTube Player script w/selectable: autoplay, W/H, default border color
    /// </summary>
    /// <param name="id">id</param>
    /// <param name="auto">bool</param>
    /// <param name="W">int</param>
    /// <param name="H">int</param>
    /// <param name="Border">bool</param>
    /// <returns>string</returns>
    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
    /// <summary>
    /// YouTube Player script w/selectable: autoplay, W/H and border color
    /// </summary>
    /// <param name="id">id</param>
    /// <param name="auto">bool</param>
    /// <param name="W">int</param>
    /// <param name="H">int</param>
    /// <param name="Border">bool</param>
    /// <param name="C1">string</param>
    /// <param name="C2">string</param>
    /// <returns>string</returns>
    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
    /// <summary>
    /// YouTube Player script w/selectable: autoplay, W/H and border color
    /// </summary>
    /// <param name="id">id</param>
    /// <param name="auto">bool</param>
    /// <param name="W">int</param>
    /// <param name="H">int</param>
    /// <param name="Border">bool</param>
    /// <param name="C1">string</param>
    /// <param name="C2">string</param>
    /// <returns>string</returns>
    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/");

        // select the youTube item to play
        sb.Append(id);

        // set autoplay options (indicates number of plays)
        if (auto) sb.Append("&autoplay=1");

        // no related items to display
        sb.Append("&rel=0");

        // set border color 1 and 2
        if (Border)
        {
            sb.Append("&border=1");
            sb.Append("&color1=" + @C1);
            sb.Append("&color2=" + @C2);
        }

        // start position
        if (Start>0) sb.Append("&start=" + Start.ToString());

        // allow full screen
        sb.Append("&fs=1");

        // closing single quote after parameter list
        sb.Append("' ");


        sb.Append("type='application/x-shockwave-flash' ");

        // add id
        sb.Append("id='youTubePlayer" + DateTime.Now.Millisecond.ToString() + "' ");
        sb.Append("allowscriptaccess='never' enableJavascript ='false' ");

        // set parameters: allowfullscreen
        sb.Append("allowfullscreen='true' ");

        // set width
        sb.Append("width='" + W.ToString() + "' ");

        // set height
        sb.Append("height='" + H.ToString() + "' ");

        sb.Append(@"></embed>");

        // get final script
        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

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 with more customization options

References

  1. YouTube embedded video player on webinfocentral.com
  2. Click/Select row in ASP.NET GridView or HTML 5 Table
  3. Hyperlinked Images in ASP.NET GridView
  4. Nested GridView controls in ASP.NET: best practices

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)

Share

About the Author

DrABELL
President Infosoft International Inc
United States United States
Dr. A. Bell has 20+ years of Software and Electrical Engineering experience: Win/Web veteran, published 300+ articles and authored 37 inventions, credited for 10+ Enterprise level projects (>250k code lines); currently focused on .NET/WPF, C#, HTML5, jQuery, SQL, 'Big Data', AI, Speech Tech and Mobile apps. He participated in App Innovation Contest (AIC 2102/2013) with several winning submissions. Sample projects/pubs follow:
  1. Edumatter M12: School Math Calculators and Equation Solvers (contest winner)
  2. Engineering Calculator VOLTA-2013 (contest winner)
  3. WebTV Project: Embedded YouTube Player (Goog #1 YouTube API for ASP.NET)
  4. Online 3 Fractions Calculator (#1 on Goog)
  5. Top-100 Digital Cameras (powered by iMark-DCAM rating engine)
  6. Engineering Calculator VOLTA-814 for Windows
  7. Pericles™ TTS-14 Text-to-Speech Synthesizer (Win)
  8. Semaphon™ SP-300 semantic phone number converter (Win)
  9. PaydayNY-2015 Payroll Tax Calculator (Win)
  10. 'Find Job Agency' Online Interactive Map (Microsoft Bing technology)
Follow on   Twitter

Comments and Discussions

 
QuestionCan this be used in a winforms application? Pin
dawiemos9-Feb-15 21:07
memberdawiemos9-Feb-15 21:07 
AnswerRe: Can this be used in a winforms application? Pin
DrABELL10-Feb-15 3:36
professionalDrABELL10-Feb-15 3:36 
QuestionA few comments Pin
Pete O'Hanlon15-Apr-13 0:09
protectorPete O'Hanlon15-Apr-13 0:09 
AnswerRe: A few comments Pin
DrABELL15-Aug-14 5:11
professionalDrABELL15-Aug-14 5:11 
QuestionDo you have a classic asp code for youtube api? Pin
cuneyttunc24-Apr-12 1:27
membercuneyttunc24-Apr-12 1:27 
AnswerRe: Do you have a classic asp code for youtube api? Pin
DrABELL15-Aug-14 5:12
professionalDrABELL15-Aug-14 5:12 
Questionfull screen Pin
shivasharmaarya20-Jan-12 10:12
membershivasharmaarya20-Jan-12 10:12 
AnswerRe: full screen Pin
DrABELL15-Aug-14 5:14
professionalDrABELL15-Aug-14 5:14 
GeneralQustion about the PlayEvent Pin
franva11-Feb-11 3:11
memberfranva11-Feb-11 3:11 
GeneralRe: Qustion about the PlayEvent Pin
DrABELL11-Feb-11 3:39
memberDrABELL11-Feb-11 3:39 
GeneralMy vote of 5 Pin
usernameCasper25-Jan-11 12:21
memberusernameCasper25-Jan-11 12:21 
great work, really nice
GeneralRe: My vote of 5 Pin
DrABELL15-Aug-14 5:14
professionalDrABELL15-Aug-14 5:14 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150520.1 | Last Updated 24 Feb 2015
Article Copyright 2009 by DrABELL
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid