Thursday, June 20, 2013

How To- Play YouTube Video in Your Website from URL only in ASP.Net

In this post, I am explaining how you can play the You Tube videos in your website using video URLs in ASP.Net without downloading the video.

In my previous posts, I explained Send Gridview Data in Email in ASP.Net using C#, VB.Net, Import Gmail contacts in ASP.Net, Export Gridview to PDF in ASP.Net with Image, Send mail in ASP.Net, Convert DataTable into List, Constructor Chainning in C#, Convert a Generic List to a Datatable, Get Property Names using Reflection in C#Hard drive information using C#SQL Server Database BackUp using C# and some other articles related to C#ASP.Net jQuery, Java Script and SQL Server.

In this post I am taking a You Tube video URL for example. So Lets start the example.

ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PlayYouTubeVideo.aspx.cs" Inherits="YouTubeVideo.PlayYouTubeVideo" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div id="divVideo" runat="server">
    
    </div>
    </form>
</body>
</html>

In the above markup, I have just take a Div control and give it an id and make it server control by adding runat="server"
Now In code behind write the following function and call it on your desire location. I have called it on Page_Load event.
C# Code

/// <summary>
/// Function to set the video frame on Div control for play
/// </summary>
protected void SetVideoForPlay()
{
   //YouTube Video URL
   string youtubeUrl = "http://www.youtube.com/watch?feature=endscreen&v=gfedwjAOMZI&NR=1";
            
  string vCode = youtubeUrl.Substring(youtubeUrl.LastIndexOf("v=") + 2);
  if (vCode.Contains("&"))
      vCode = vCode.Substring(0, vCode.LastIndexOf("&"));

   string sHtml = @"<object width='{0}' height='{1}' data='http://www.youtube.com/v/{2}&autoplay=0' codetype='application/x-shockwave-flash'>
  &ltparam name='movie' value='http://www.youtube.com/v/{2}&autoplay=0'></param></object>";
 //define frame size
 string sWidth = "500px";
 string sHeight = "500px";

 //insert code to the Div
 divVideo.InnerHtml = String.Format(sHtml, sWidth, sHeight,vCode);
}
Output
Play YouTube Video in Your Website from URL only in ASP.Net
I hope this article will be helpful for you. I would like to have any feedback from you. Your valuable feedback, question, or comments about this article are always welcome.

No comments:

Post a Comment

If You Enjoyed This Post Please Take 5 Seconds To Share It.

^ Scroll to Top hgpromo