Friday, 3 February 2012

Playing Videos like YouTube and Thumbnail Creation in ASP.Net

If you want to play video like youtube in your ASP.Net application what will you do? Can you able to generate thumbnail for the video programmatically? How did you play converted video?? All these are for Free of cost. No need to buy any software then how??. 

This article will provide solutions for the above questions. Generally we can see some video sites like youtube. Here we can watch streaming media. But when you upload a wmv file into server and try to play it. What happen? If the video is long it will take time to play. For this reason we have to convert the video to a streaming media(like swf) so that when the page is opened automatically video playing started. 

For this we have to convert the video which is uploaded by the user to swf. Then only we can able to play the video quickly. In order to convert the video we will use a software called FFMPEG. It’s open source software you can download this software from here.

Using FFMPEG we can able to generate thumbnails for the video what ever we are uploading. By using FFMPEG’s API we can perform various operations for the videos and audios.
In order to start this Application first we have to import following name spaces…

using System.IO;
using System.Diagnostics;
When User Clicks on Upload button then we have to perform following tasks.
  • Check the Format of Video
  • Convert the Video to flv format with FFMPEG
  • Generate a Thumbnail for the uploaded video
  • Delete the original video.

  • Check the Format of Video

    Here I am using Regular Expression to check the video format. I want to upload only wmv, mpeg, or avi format videos. Here is the regular expression


    <asp:RegularExpressionValidator id="req1" runat="server"

    ErrorMessage="Only wmv, avi or mpeg files are allowed!"

    ValidationExpression="^(([a-zA-Z]:)(\\{2}\w+)\$?)(\\(\w[\w].*))+(.wmv.avi.mpeg.MPEG)$"

    ControlToValidate="FileUpload1" Display="dynamic"></asp:RegularExpressionValidator>

  • Convert the Video to flv format with FFMPEG
    To Convert our video to SWF format FFMPEG need File Name, File Arguments. File Name is the name of the FFMPEG folder with full path. Arguments can be write as..
  • The general syntax is ..
    ffmpeg [[infile options][@option{-i} infile]]... {[outfile options] outfile}...

    filargs = "-i " + inputfile + " -ar 22050 " + outputfile;
    To run the FFMPEG exe we have to start a Process. This can be write as..
    Process proc;
    proc = new Process();
    proc.StartInfo.FileName = spath + "\\ffmpeg\\ffmpeg.exe";
    proc.StartInfo.Arguments = filargs;
    proc.StartInfo.UseShellExecute = false;
    proc.StartInfo.CreateNoWindow = false;
    proc.StartInfo.RedirectStandardOutput = false;
    try
    {
    proc.Start();
    }
    catch (Exception ex)
    {
    Response.Write(ex.Message);
    }
    proc.WaitForExit();
    proc.Close();

    • Generate a Thumbnail for the uploaded video

      For the thumbnail we have to provide path to where we have to save our thumbnail. Here is code for thumbnails..

  • //Create Thumbs
    string thumbpath, thumbname;
    string thumbargs;
    string thumbre;
    thumbpath = AppDomain.CurrentDomain.BaseDirectory + "Video\\Thumb\\";
    thumbname = thumbpath + withoutext + "%d" + ".jpg";
    thumbargs = "-i " + inputfile + " -vframes 1 -ss 00:00:07 -s 150x150 " + thumbname;
    Process thumbproc = new Process();
    thumbproc = new Process();
    thumbproc.StartInfo.FileName = spath + "\\ffmpeg\\ffmpeg.exe";
    thumbproc.StartInfo.Arguments = thumbargs;
    thumbproc.StartInfo.UseShellExecute = false;
    thumbproc.StartInfo.CreateNoWindow = false;
    thumbproc.StartInfo.RedirectStandardOutput = false;
    try
    {
    thumbproc.Start();
    }
    catch (Exception ex)
    {
    Response.Write(ex.Message);
    }
    thumbproc.WaitForExit();
    thumbproc.Close();
  • Delete the original video.
    Once the conversion process is completed we delete wmv file. Here is the code.
    File.Delete(inputfile);
  • Here the most important thing is “Permissions”. In order to convert the video and generate the thumbnails we have to provide all permissions to our application. Especially for the folder where your going to save the videos and thumbnails.
    If you’re using FFMPEG in Remote server then you have to give all permissions to FFMPEG folder also. Because here we are running an exe to convert the videos.
    When ever you upload videos more then 4096 KB, ASP.Net does not allow you to upload the video because It’s the Max HTTP Request size for any application. If you want change the HTTP request size you have to change the “maxRequestLength” in web.config section. Here is the complete code..

    <system.web>
    <httpRuntime
    executionTimeout="110"
    maxRequestLength="30000"
    requestLengthDiskThreshold="80"
    useFullyQualifiedRedirectUrl="false"
    minFreeThreads="8"
    minLocalRequestFreeThreads="4"
    appRequestQueueLimit="5000"
    enableKernelOutputCache="true"
    enableVersionHeader="true"
    requireRootedSaveAsPath="true"
    enable="true"
    shutdownTimeout="90"
    delayNotificationTimeout="5"
    waitChangeNotification="0"
    maxWaitChangeNotification="0"
    enableHeaderChecking="true"
    sendCacheControlHeader="true"
    apartmentThreading="false" />
    </system.web>
    Now you can able to upload videos upto 30MB.
    How to Play Video:
    Using swf player we can play the video. In the sample application you can find this player. For this player we have to give the source file name with correct path. You can find play.aspx file in source code to know more about how to play the videos.


    In Part-I, I am explained how to convert the video from one format to another format and generating thumbnails. In Part-II I am going to explain how to bind this thumbnail to Gridview or DataList dynamically from Database and how to play the videos.
    Note: In the sample I did not place the ffmpeg software due to the size.(Its around 10MB)
    You can download for here:ffmpeg.rar
    Downloadm Source Code





    Playing Videos - Part II

    Friday, September 26, 2008

    In Playing Videos-I I have been explained to upload a videos, how convert video from one format to another format and how to generate thumbnail automatically. In this post I am going to expalin how to retrive the videos and thumbnail dynamically from database. 

    First I am starting with DataBase part, Here I am creating a table called videos. And it contains 3 fields the are
    Video_ID,Video_File,Video_Image. You can see the table design pic.



    Here "Video_File" field contains Name of the video with extension. Here I am going to store the file name only. But the video file is located in server. "Video_Image" is the thumbnail file name with extension. Same as video thumbnail also located in server. 

    When I am uploading video, I am going to save the videofilename, Image name in database. Here I used very simple code to insert this details. Here is the code..... 



    private void Savedetails()
    {
    string filename, imgname;
    filename = Session["outputfile"].ToString();
    imgname = Session["thumbname"].ToString();
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestConnectionString"].ConnectionString);
    con.Open();
    SqlCommand cmd = new SqlCommand("insert into video(Video_File,Video_Image) values('" + filename + "','" + imgname + "')", con);
    cmd.ExecuteNonQuery();
    cmd.Dispose();
    con.Close();
    }

    You can use stored procedures in back end for the better performance. Once the video uploading is finished then I am going to show these details in DataList. Here is the code to bind the video thumbnail in Datalist


    <asp:DataList ID="dtlstVideo" runat="server" GridLines="Vertical"
    RepeatColumns="2" RepeatDirection="Horizontal" BackColor="White"
    BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="5">
    <ItemTemplate>
    <td><a href="Play.aspx?vid=<%# DataBinder.Eval(Container.DataItem, "Video_ID") %>">
    <img src="Video/Thumb/<%# DataBinder.Eval(Container.DataItem, "Video_Image") %>" border="0" />
    </a>
    </td>
    </ItemTemplate>
    <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
    <AlternatingItemStyle BackColor="#DCDCDC" />
    <ItemStyle BackColor="#EEEEEE" ForeColor="Black" />
    <SelectedItemStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
    </asp:DataList>



    when the user click on the datalist it will be redirected to play.aspx with video ID as the query string. In the
    play.aspx page I am goign to bind the SWF player with video file name. Here is the code...


    string vid,vfname;
    protected void Page_Load(object sender, EventArgs e)
    {
    vid = Request.QueryString["vid"].ToString();
    DataSet dst = (DataSet)Session["videods"];
    DataRow[] dw = dst.Tables[0].Select("Video_ID= '"+ vid +"'");
    if (dw.Length > 0)
    {
    vfname = dw[0]["Video_File"].ToString();
    }
    string plyr = "<embed src='Players/flvplayer.swf' width='425' height='355'
    bgcolor='#FFFFFF' type='application/x-shockwave-flash'
    pluginspage='http://www.macromedia.com/go/getflashplayer'
    flashvars='file=Video/SWF/" + vfname + "&autostart=false&frontcolor=0xCCCCCC&
    backcolor=0x000000&lightcolor=0x996600&showdownload=false&showeq=false&repeat=false&
    volume=100&useaudio=false&usecaptions=false&usefullscreen=true&usekeys=true'>
    </embed>";
    plh.Controls.Add(new LiteralControl(plyr));
    }

    You can see the screen shot of playing a video dynamically..

    Source Code

    No comments:

    Post a Comment