Click here to Skip to main content
Licence CPOL
First Posted 2 Oct 2009
Views 49,348
Downloads 2,921
Bookmarked 64 times

YouTube™ API for ASP.NET

By | 2 Oct 2009 | Article
YouTube™ API for ASP.NET, AJAX-extended (C#).

YouTubeAPI_CodeProject

Introduction

Embedded Video Players, based either on Adobe Flash™ or Microsoft Silverlight™ technology, could dramatically improve web page aesthetic appeal and overall user experience. This article demonstrates the coding technique for embedding the popular YouTube™ Video Player (which is built on the above mentioned 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

A functional demo of the YouTube™ Player embedded in an ASP.NET web page is available at: www.webinfocentral.com/RESOURCES/VideoAudio.aspx.

Background

The Embedded Video Player would be capable of streaming (playing back) the audio/video content, available from the www.youtube.com website. You do not need to subscribe/logon to the site in order to utilize this feature. The content to be played is encrypted into a query string, looking like a random set of characters, for example: x_4CNvG1Q_M, and the corresponding full address string should look like: http://www.youtube.com/watch?v=x_4CNvG1Q_M (which is 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:

  1. Create or open an ASP.NET Web Site using either Microsoft Visual Studio 2008 (any edition) or the Visual Web Developer 2008 Express edition.
  2. Download the compressed (.zip) file. Extract the components into your web application directory.
  3. Set the embedded YouTube™ Video Player dimension: W/H.
  4. Customize the YouTube™ Video Player border options.
  5. 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>
                <!-- ALL CONTENT IS SHOWN FOR DEMO PURPOSE ONLY-->
                <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="http://www.webinfocentral.com/RESOURCES/VideoAudio.aspx" 
              target="_blank">www.webinfocentral.com</a>
          </h4>
          <hr />
        </form>
    </body>
</html>

The code-behind:

//****************************************************************************
// Module           :   Default.aspx.cs
// Description      :   YouTube API for ASP.NET: code behind
// Developer        :   Alexander Bell (Infosoft International Inc)
// DateCreated      :   09/10/2009
// LastModified     :   09/12/2009
//****************************************************************************
// DISCLAIMER: This Application is provide on AS IS basis without any warranty
//****************************************************************************
//****************************************************************************
// TERMS OF USE     :   ALL YouTube CONTENT IS SHOWN AS DEMO SAMPLE ONLY
//                  :   You can use it at your sole risk
//****************************************************************************
using System;
public partial class _Default : System.Web.UI.Page 
{
    // player width
    private int _W = 640;
    // player height
    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 = "";
            // Autostart
            try {
                qry = "auto"; 
                qry = (Request.QueryString[qry] == null) ? "" : Request.QueryString[qry];
                if (qry != "") { auto = int.Parse(qry); }
            } catch { }
            // Item index
            try {
                qry = "item"; 
                qry = (Request.QueryString[qry] == null) ? "" : Request.QueryString[qry];
                if (qry != "") { idx = int.Parse(qry); }
            } catch { }
            #endregion
            // get value from the list for 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, 0, _W, _H);
        }
    }
}

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.

A video item to play could be passed via a Web Query as an index corresponding to the dropdown cmbPlaylist control. The auto-play option could also be set via a Web Query (see the example): www.webinfocentral.com/RESOURCES/YouTubeMusicVideo.aspx?item=2&auto=1.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

DrABELL

Chief Technology Officer
Infosoft Int'l
United States United States

Member

Dr. A. Bell (aka DrABELL), hi-tech consultant living in the US, has more than 20 years of software and electronic engineering experience. He published more than 100 technical articles and authored 37 inventions. Dr. Bell is the Windows/Internet technologies veteran, currently focused on: .NET,Mobile,Java,C#,SQL,HTML5,CSS3. He developed the most popular Silverlight Media Player (#1 Goog) and 3 Fractions Calculator (also #1 on Google/Bing/Yahoo). Sample online projects:
  1. Embedded youTube Player: ASP.NET API
  2. Semantic Analyzer
Popular hi-tech articles:
  1. WebTV Project: Embedded YouTube Player
  2. Personal computer 2011: mostly USB 3.0, SATA 3.0, DDR 3 plus SSD/HDMI
  3. Introducing the unit of internet social network efficiency: 1 Zuck
  4. Internet leader 2010: Facebook. See the entire Top10 list
  5. How to select web browser and check its capabilities
  6. SQL generates large data sequence
  7. Aggregate Product function extends SQL
  8. HTML 5, CSS 3 and Inflation Calculator
  9. RIA: embedding YouTube
  10. RIA: Silverlight™ media player
  11. RIA: HTML 5 video player


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralNEW!! Embedded YouTube Player (WebTV project, Beta) PinmemberDrABELL11:32 5 Jun '11  
GeneralYouTube® video playback customization technique PinmemberDrABELL6:40 2 Feb '11  
GeneralShort URL PinmemberDrABELL5:41 3 Jan '11  
GeneralMy vote of 5 PinmemberMehedi_Hasan10:33 28 Oct '10  
GeneralRe: My vote of 5 PinmemberDrABELL6:20 7 Dec '10  
Generalsome query Pinmembermakhar17:47 22 Jul '10  
GeneralRe: some query PinmemberDrABELL6:32 7 Dec '10  

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.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 2 Oct 2009
Article Copyright 2009 by DrABELL
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid