Click here to Skip to main content
Click here to Skip to main content

Play Embedded YouTube Videos Randomly

, 13 Sep 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
Illustrate how to embed a YouTube video into a web page, build a random play list, and launch a video on the fly.

Introduction

I developed a web application a while ago that randomly plays embedded YouTube videos on a web page. When a user views the page, a list of image links randomly selected from a video collection shows up. The user then clicks on any of the images to start a video. If the page is refreshed, a new random list is generated. The application is implemented using the YouTube embedded video player, SQL Server, ASP.NET server controls, and the HTML Document Object Model. There are a few tricks worked out along the way.

In this article, I'll explain how it is done. A demo application has been prepared. A screenshot is shown below. The application is coded in Visual Studio 2010 and SQL Server 2008 Express Edition. For previous versions of Visual Studio, you may need to recreate a project and then add files to it.

PlayingVideo.jpg

Embed YouTube Video into a Web Page

Let's start with how a YouTube video is embedded into a web page. Luckily, YouTube.com has made it relatively easy. To do this, you need to acquire the embedded video code from YouTube.com, which is available at two locations, the management area and the video viewing area.

When you log into your YouTube account and then upload a video, the embedded code is automatically generated for you and displayed in the "Sharing options" section on the management interface, as illustrated in the image below.

EmbedCode_Admin.jpg

The code looks like:

<object width="480" height="385">
<param name="movie" 
   value="http://www.youtube.com/v/ITswHbJPHhQ?fs=1&amp;hl=en_US&amp;rel=0"></param>
<param name="allowFullScreen" value="true"></param>
<param name="allowscriptaccess" value="always"></param>
<embed src="http://www.youtube.com/v/ITswHbJPHhQ?fs=1&amp;hl=en_US&amp;rel=0" 
   type="application/x-shockwave-flash" allowscriptaccess="always" 
allowfullscreen="true" width="480" height="385"></embed></object>

It consists of a video URL and its associated parameters. Copy and paste the code on to a web page and it is done. The video is embedded on the page now. As you can see, the parameters such as "movie", "allowFullScreen", and "allowscriptaccess" are included by default. However, the interface does not give you a way to customize the code. If you want a video to behave differently, you have to edit the code manually to add or remove parameters.

When viewing a video at YouTube.com, an "<Embed>" button is present right below the video. Click on the button, and a code window is revealed and lists the embedded video code. The image below illustrates the code window.

EmbedCode_View.jpg

The code shown here is exactly the same as that in the management area. This interface gives us several check boxes for customization. These options would add more parameters to the code. They change the look and feel of the player. However, you'll notice later that none of them are critical for our purpose. Therefore, we need to explore other parameters to modify the behavior of our videos. YouTube.com provides plenty of parameters for a developer to work with. The names and descriptions of the YouTube Embedded Player parameters are listed on this web page: http://code.google.com/apis/YouTube/player_parameters.html. Two parameters in particular are of our interest: autoplay="1"and wmode="transparent". The explanation is to be given in the next section.

Generate a Random Play List

Looking at the screenshot at the beginning of this article, the play list consists of six HTML image links created from randomly selected data stored in a Microsoft SQL Server 2008 Express Edition database. The database has one table, named "VideoInfo". The data structure and its sample data are shown in the images below. The columns Title and ImagePath are used for creating the image links, while EmbeddedCode, Width, and Height are required for launching a video.

TableDesignView.jpg

TableDataView.jpg

To randomly retrieve a number of records from a SQL database is, in fact, quite easy. The trick is in the "Order By" clause. When ordered by the NewID() SQL function in conjunction with the keyword "top", a given number of records are randomly selected. This task is accomplished through a Stored Procedure call as shown below, in which 6 random records are returned.

StoredProc.jpg

Now, let's take a look at how the image links are constructed. An HTML image link for launching an embedded YouTube video is a regular HTML anchor element, and would resemble this pattern:

<a href="#" onclick="PlayVideo('EmbeddedCode',' videoWidth', 'videoHeight');">
<img title="Title" src="images/ImagePath" width="imgWidth" height="imgHeight" /></a>

Upon a click on the link, a JavaScript function "PlayVideo()" is executed . Looking at the PlayVideo.aspx page in the demo app, to construct a link like this, an ASP.NET DataList server control is utilized. Pieces are put together inside the <ItemTemplate> of the DataList. See the code below.

<asp:DataList ID="dlVideoLinks" runat="server" 
        RepeatDirection="Horizontal" RepeatLayout="Flow">
<ItemTemplate>
<a href="#" onclick="PlayVideo('<%# BuildVideoCode((string)Eval("EmbeddedCode")) %>', 
   <%# Eval("Width") %>, <%#Eval("Height") %>);"><%#DisplayImage(
       (string)Eval("ImagePath"), (string)Eval("Title")) %></a>
</ItemTemplate>
</asp:DataList>

The DataList is filled with randomly selected data in the Page_Load() server-side event. The code for data retrieval listed below is straightforward and descriptive, but does not need an explanation.

using (SqlConnection con = new SqlConnection(
   ConfigurationManager.ConnectionStrings["VideoDatabase"].ConnectionString))
{
    con.Open();
    //storedproc VideoInfo_get retrieve 6 records randomly from database
    SqlCommand cmd = new SqlCommand("VideoInfo_get", con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable tbl = new DataTable("VideoData");
    da.Fill(tbl);

    lblRefresh.Text+="<a href=\"PlayVideo.aspx\">Refresh Play List</a>";

    dlVideoLinks.DataSource = tbl;
    dlVideoLinks.DataBind();
}

However, during data binding, the returned data from the database is not directly bound to the DataList, but through two server-side function calls, BuildVideoCode() and DisplayImage(). See the listing below. These functions properly modify the existing embedded video code obtained from YouTube.com and build image links accordingly.

public string BuildVideoCode(string embeddedCode)
{
    //add autoplay=1 and wmode=transparent, replace bouble quote with html equivalent
    return embeddedCode.Replace("fs=1", "fs=1&autoplay=1")
                .Replace("<param name=\"allowFullScreen\" value=\"true\"></param>", 
                      "<param name=\"allowFullScreen\" value=\"true"></param>
                      <param name=\"wmode\" value=\"transparent\"></param>")
                .Replace("type=\"application/x-shockwave-flash\"", 
                      "type=\"application/x-shockwave-flash\" wmode=\"transparent\"")
                .Replace("\"", "&quot;");
}

public string DisplayImage(string imgPath, string title)
{
    //build the image html code which is used for video link
    return "<img src=\"images/" + imgPath
                + "\" width=\"75\" height=\"60\" border=\"0\" title=\"" 
                + title + "\"/>";
}

As mentioned earlier, two more parameters need to be added to the embedded video code, autoplay="1" and wmode="transparent".

When autoplay is set to be "1", an embedded video starts to play as soon as it shows up on a web page. Otherwise, the user has to click a Play button on the video. By default, the autoplay parameter is not included in the code and the value of "0" is assumed.

It should also be noted that when an embedded video is played, although you are able to stop it by clicking the Stop button, you are not able to close the player. The player continues its download for the video even though the video is paused or stopped. Therefore, we need to implement a mechanism to allow the user to close the video player. Another behavior is that an embedded video always stays on top of all other HTML elements on a page. The z-index in the stylesheet does not have any effect on it. As a result, an HTML element that you want to display inside an embedded video frame is covered by the video, but is not visible. This is where the parameter wmode comes handy. When it is set to be "transparent", the HTML element added to the video becomes visible. In our case, we'll add a "close" button at the top right corner of the video, which removes the current video from the page upon a click. This is the reason we want to set the wmode to be "transparent".

The BuildVideoCode() function adds the parameters autoplay and wmode to the embedded video code. It simply replaces an existing parameter string with the one containing the existing one plus an additional parameter. For example, to add autoplay="1", we replace "fs=1" with "fs=1&autoplay=1". Furthermore, double quotes included in the embedded video code should be replaced with an HTML equivalent "&quot;". This is to comply with the HTML specification for the JavaScript function called in an HTML anchor element since a literal double quote in a parameter passed into a JavaScript function is illegal in HTML code. The DisplayImage() function constructs an HTML image to display in a link.

The HTML code of a constructed HTML image link that plays an embedded YouTube video would look like the following:

<a href="#" onclick="PlayVideo('<object width=&quot;480&quot; height=&quot;385&quot;>
<param name=&quot;movie&quot; 
   value=&quot;http://www.youtube.com/v/e1NAmBAbOTM?fs=1&autoplay=1&amp;hl=en_US&quot;>
</param>
<param name=&quot;allowFullScreen&quot; value=&quot;true&quot;></param>
<param name=&quot;wmode&quot; value=&quot;transparent&quot;></param>
<param name=&quot;allowscriptaccess&quot; value=&quot;always&quot;></param>
<embed src=&quot;http://www.youtube.com/v/e1NAmBAbOTM?fs=1&autoplay=1&amp;hl=en_US&quot; 
   type=&quot;application/x-shockwave-flash&quot; 
   wmode=&quot;transparent&quot; allowscriptaccess=&quot;always&quot; 
   allowfullscreen=&quot;true&quot; width=&quot;480&quot; 
   height=&quot;385&quot;></embed></object>', 480, 385);">
<img src="images/Lady_di.jpg" width="75" height="60" border="0" title="Lady di"/></a>

It can be seen that a lengthy embedded video code is one of the parameters passed into the JavaScript function. All literal double quotes are replaced by the HTML code "&quot;".

Launch Embedded YouTube Video

With a play list built in the previous section, let's now take a look at how an embedded video is launched.

Here is the programming logic. Upon a client-side click, an HTML div element is created. A piece of embedded video code is assigned to the div as its innerHtml. The div is then positioned and displayed on the web page. Consequently, the video code inside the div goes into effect and the video starts to play. This process is initiated through a client-side JavaScript function call, PlayVideo(), as listed below:

function PlayVideo(videoCode, width, height) {
    //if a video is playing, close it first
    var VideoDiv = document.getElementById('video-div');
    if (VideoDiv != null) {
        RemoveDiv();
    }
    //play a new video
    CreateVideoDiv('video-div', 'video-div', videoCode, width, height);
    CreateCloseDiv("close-div", "close-div", 
       "<a href=# onclick=RemoveDiv();>
            <img src=\"images/close.jpg\" width=\"16\" 
            height=\"16\" border=\"0\"/></a>", width, height, 16, 16);

}

The function takes three parameters, in which videoCode is the modified embedded YouTube video code, and width and height are the dimensions of the video. It first checks to see if there is a video on the web page or not. If yes, it removes it by calling the RemoveDiv() function. And then it calls the CreateVideoDiv() function to create a new div on the fly. The created div contains the embedded video code as its innerHtml, and has the same size as the dimensions of the video. It is positioned at the center of the browser window. Its style attribute "display" is set to be "block", which makes the div visible on the page. That is all that needs to be done to play a video.

Next, the CreateCloseDiv() function is executed. This creates another div with a size of 16x16px. It holds a "close" image link (close.jpg) as its innerHtml, and is placed at the top right corner of the video div. As discussed in the last section, an embedded YouTube video may be paused or stopped but cannot be closed. This small div simulates a "close button", and provides an interface for a user to remove an active video from the web page as needed. When it is clicked, the client-side RemoveDiv() function is executed, and both the video div and the close button are removed from the current page.

The code for creating a video div and a "close"div, and for removing a div is shown below:

function CreateVideoDiv(id, className, contentToDisplay, width, height) {
   //create a div and center it inside the browser window
    var NewDiv = CreateDiv(id, className, contentToDisplay, width, height);
    NewDiv.style.marginLeft = -(parseInt(width) / 2) + "px";
    NewDiv.style.marginTop = -(parseInt(height) / 2) + "px";
}

function CreateCloseDiv(id, className, contentToDisplay, 
         videoWidth, videoHeight, closeImageWidth, closeImageHeight) {
    //place the "close" image at the top right corner of the video div
    var NewDiv = CreateDiv(id, className, contentToDisplay, 
                           closeImageWidth, closeImageHeight);
    NewDiv.style.marginLeft = (parseFloat(videoWidth) / 2) - 
                               parseFloat(closeImageWidth)*1.5 + "px";
    NewDiv.style.marginTop = -(parseFloat(videoHeight) / 2) + 
                               parseFloat(closeImageHeight)/2 + "px";
}

function CreateDiv(id, className, contentToDisplay, width, height) {
    var NewDiv = document.createElement("div");
    NewDiv.id = id;
    NewDiv.className = className;
    NewDiv.innerHTML = contentToDisplay;
    NewDiv.style.position = "absolute";
    NewDiv.style.width = width + "px";
    NewDiv.style.height = height + "px";
    NewDiv.style.top = "50%";
    NewDiv.style.left = "50%";
    NewDiv.style.display = "block";
    document.body.appendChild(NewDiv);

    return NewDiv;
}

function RemoveDiv() {
    var mydiv = document.getElementById("video-div");
    document.body.removeChild(mydiv);
    var mydiv = document.getElementById("close-div");
    document.body.removeChild(mydiv);
}

Examining the code closely, both CreateVideoDiv() and CreateCloseDiv() call the function CreateDiv(). This function utilizes the HTML Document Object Model to create a new div on the fly. For the video div, style definition similar to the following is applied in order to position a video at the center of a browser window.

#video-div
{
    position:absolute;
    top:50%;
    left:50%;
    width:400px;
    height:300px;
    margin-left:-200px;
    margin-top:-150px; 
    display:block;
}

You may certainly modify the function to place a video at a different location. The code for closing a video is self explanatory.

Conclusion

I have discussed how a YouTube video is embedded into a web page, how to generate a random play list, and how to launch an embedded YouTube video on the fly. With minor modifications to the embedded video code acquired from YouTube.com as well as creation and manipulation of HTML div elements using the HTML Document Object Model, we are able to build a web application to randomly play embedded YouTube video. In addition, a methodology for closing a video is also demonstrated.

Videos used in the demo application are selected from YouTube.com for illustration purposes only. All rights belong to their original authors.

License

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

Share

About the Author

Tomz_KV
Web Developer
United States United States
Web & Database Developer. Design and implement web and database applications utilizing Microsoft and other development tools.

Comments and Discussions

 
QuestionIs Possible embed other video link other than youtube? Pinmembervignesh95710-Jul-14 1:10 
AnswerRe: Is Possible embed other video link other than youtube? PinmemberTomz_KV10-Jul-14 1:42 
GeneralRe: Is Possible embed other video link other than youtube? Pinmembervignesh95710-Jul-14 1:50 
GeneralRe: Is Possible embed other video link other than youtube? PinmemberTomz_KV10-Jul-14 1:58 
GeneralRe: Is Possible embed other video link other than youtube? Pinmembervignesh95710-Jul-14 17:17 
GeneralRe: Is Possible embed other video link other than youtube? PinmemberTomz_KV11-Jul-14 2:08 
Newsthere is a better solution PinmemberShadi Abu-Hilal8-Oct-12 6:35 
GeneralRe: there is a better solution PinmemberTomz_KV8-Oct-12 6:56 
QuestionAutoplay not working with mp4 file. PinmemberMukund Thakker19-Mar-12 0:23 
AnswerRe: Autoplay not working with mp4 file. PinmemberTomz_KV19-Mar-12 3:24 
GeneralMy vote of 4 PinmemberMr.Sourav.Maitra27-Feb-12 18:57 
QuestionSQL changing to XML databound Pinmembervipernet0224-Jun-11 11:53 
AnswerRe: SQL changing to XML databound Pinmembervipernet0224-Jun-11 12:08 
AnswerRe: SQL changing to XML databound PinmemberTomz_KV24-Jun-11 13:10 
Questionpaginate yt videos Pinmemberbozzo2223-Jun-11 4:41 
Questionreally nice demo Pinmemberbozzo2223-Jun-11 4:17 
AnswerRe: really nice demo PinmemberTomz_KV23-Jun-11 4:32 
QuestionUnix/Linux Server? Pinmemberfasterthanyours21-Sep-10 10:13 
AnswerRe: Unix/Linux Server? PinmemberTomz_KV21-Sep-10 10:23 

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 | Mobile
Web03 | 2.8.141015.1 | Last Updated 13 Sep 2010
Article Copyright 2010 by Tomz_KV
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid