Playing Videos like YouTube and Thumbnail Creation in ASP.Net - I

Monday, September 22, 2008
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


    85 comments:

    satya said...

    Hi Ram,its Very interesting,keep doing man

    Anonymous said...

    well unfortunately link for source doesn't work. Can u post it again?

    fbgfcb said...

    Thumbnail for the uploaded video
    is not saving at his destination folder.

    Neil said...

    Hi Great post i have followed it and implemented it into my application and it all works great i am even saving the files now to a dedicated NAS Server :-)

    When will you post Part 2?? i am in need of displaying my results in a repeater and then showing the dynamically in the flash player?

    Unknown said...

    Hi Ram,

    I tried to implement this code but did not work for me. The problem I am facing is that; it does not create swf and thumb image in the specified path. I think the process of converting it by using ffmpeg is not working for me. Your help will be highly appreciated. Thanks in advance. Imran

    Unknown said...

    Hai Ram,
    Its fine work.
    But, if i am host into the server its not working(but it works in IIS). The files are not created on the destination folder. Please coutl you help me to resolve this error..

    Nikki said...
    This comment has been removed by the author.
    Nikki said...

    Hi Ram,

    Thanks for your Web application.
    It works, I can convert .wmv to .flv, but it's impossible to convert .mpg to .flv !??

    I think that's following code must change :
    filargs = "-i " + inputfile + " -s 400x300 -ar 22050 " + outputfile;
    ...but I don't know what !

    Can you help me ?

    See you,

    Rémy

    gulrej said...

    I tried to implement this code but did not work for me. The problem I am facing is that; it does not create swf and thumb image in the specified path.

    Ramky said...

    Hii gulrej..
    I think U not Included the FFMPEG folder. Plz check it. If u have any doubt plz send me a mail..ok..

    dheerajms said...

    Hi,
    Does the same logic/code work with 64-bit OS & libraries? Thanks!

    sha said...

    doesn;t save filespls help me

    Mahesh Dimble said...

    hi,

    A problem with flashplayer,the uploaded video playing in loop.I am working with .net 3.5

    Thanks.

    Unknown said...

    Hey Ram,


    I tried to download the source code. i thk link is breaked. can u chek once.


    Also can u provide the lonk to download FFMPEG .

    Thanks
    Praveen

    Unknown said...
    This comment has been removed by the author.
    Mr. Halim said...

    Greta post Ramky.

    I also has problem like previous friend where the swf and thumb file was not created without any error happen. After some searching on internet I found that the string fileargs need to include "\" char with some modification on it. see example below:

    filargs = "-i \"" + inputfile + "\" -deinterlace -ab 32 -r 15 -ar 22050 -ac 1 \"" + outputfile + "\"";

    thumbargs = "-i \"" + inputfile + "\" -f image2 -vframes 1 -ss 3 -s 150x130 \"" + thumbname + "\"";

    Thanks
    visit my blog at myjavaland.wordpress.com

    venkata said...

    its excellent and it helped me a lot ,keep going on ram

    Unknown said...

    i noticed that when trying to create a thumbnail for an FLV file with alpha channel, the thumbnail is black, any ideas?

    Anonymous said...

    Hi Ram,
    Firstly congrats for achieving this.
    i've downloaded the entire source code from your blog and ran it on my localhost which is working fine without any errors,
    But when i input .avi file it is converting it to .swf but of 0KB size and the thumbnail is not being saved,
    Can you please let me know where the issue is? As i need to integrate this to my project..
    Congrats Again,
    Many Thanks,
    Pavan.P

    Display name said...

    Is this generating an swf file from the video or an flv file ? Where you are mentioning the file type ? Can we crate a thuumbnail image from an swf file using ffpeg ?

    ravikumar said...

    Hey,
    this is nice but i need the partII i.e.To play Video file, can u please help me

    Vidya said...

    Hi Ram
    Wonderful Post. It helpmed me alot. but the problem is,
    Process is not working Correctly.
    i just copy ffmpeg to my project and run the project and change web.config and all other files paths.input file is created but no SWF and thumbnails. Please help me. Process is started but didnt generate any SWF.

    Unknown said...

    Really Nice....Congrats....

    Atif said...

    nice work.....

    i have one question...

    is it only supporting the mentioned file types? i mean .wmv .avi .mpeg .MPEG

    Please answer....

    Unknown said...

    Hi Ram,

    It is interesting code and it is greate help for developer.Greate job.

    I am working on a project which uses sitecore server for developement. It has same requirement - user can upload any video which needs to convert into flash and play like you tube.

    Is it possible to convert all video file to swf ? I tried to convert MP3, swf is created ,unfortunately thumb image is not created for this file. Am i missing anything ?

    Thanks in advance.

    SohelElite said...

    Great work & thanks for sharing its work absolutely fine!

    Unknown said...

    I tried running the code. Its not generating swf file and thumbnails for me. Neither its giving any error.
    Am i missing anything?

    SoftloverHKS said...

    Gr8 post man........it really made my day....was looking 4 this since a long time.

    Unknown said...

    I tried to implement this code but did not work for me. The problem I am facing is that; it does not create swf and thumb image in the specified path.

    Please help as soon as possible

    Thanking you advance

    Unknown said...

    hai,u have done a great job,actually i am soring video file in sqlserver2005 as binarydata instead of storing in appication folder,but u wrote embed data in codebehind with file name="Eati.swf", but i want this in html with value='<%# handler.ashx?id=' ,please find a solution to this,
    please send code to my emailid,
    my emailid is faiyazjpnce@gmail.com

    thanks in advance

    Prasanth Kumar said...

    I have tried with it but works for only ur file,but when i upload my file ,its saved as 0 bytes

    Unknown said...

    Hi Ram
    I implemented your code.It was not creating thumb and swf.I included ffmpeg and Video folder.Pleaes help in that
    Thanks & regards
    shanwaj

    Harshad said...

    I convert the file in WMV format and save that in particular folder Name Video.(e.g. ~/video/123.wmv)
    Now I want to pass the value to the player which is made by me.

    I hope u help me in this.
    Thanking you,
    Harshad

    Ramana said...

    Hi Ram,This Link Is Not Working.......Can U Ckeck It Once......

    Anonymous said...

    Hi.. the link to download the source is not working, can u plz share again.

    Ramky said...

    Hi Ramana, Download link working fine. Pls check once again...

    Unknown said...

    Thanks so much :)

    sha said...

    Masha Allah! its working fine.
    Thanks a lot.

    soujanya said...

    That's great. It is working fine.

    soujanya said...

    thanks a lot

    Unknown said...

    Hi Ram, Really great post. Helped me a lot to get the basic idea about how to use FFMPEG from ASP .NET code. Now with FFMPEG I am generating thumbnails at different time interval.

    Ramky said...

    Ur Welcome :)

    harsha.vemula said...

    hello sir,
    I used your code for creating thumbnails.but it raising error in the part of Convert the Video to flv format with FFMPEG(The system cannot find the path specified).I think it is in the line:

    proc.StartInfo.FileName = spath + "\\ffmpeg\\ffmpeg.exe";

    and am missing something on working with ffmpeg,just i added ffmpeg.exe,pthreadGC2.dll,SDL.dll into bin folder of my Userinterface(my application is in 3-tier architecture).please reply me.
    Thanks in advance.

    Anonymous said...

    Hi , This code is working fine in local system . But when upload on web server , This code is not working , please help me

    KatyRose69 said...

    It's probably not going to work for most people - this is nice code and works beautifully on my local machine - but it's *very* unlikely to work in a shared hosting environment.

    99% of hosts won't allow you to run ffmpeg.exe from their servers, which means you're stuck ( like me :( )

    Generic Cialis said...

    Great tool, I was looking for something like this for a long time.

    Rayapati said...

    can we capture images of embed videos(means can we give source file for ffmpeg as embed video tag from youtube)?

    Unknown said...

    Thanks to Ram and Halim the code worked very well with Halim's modification;

    inputfile=@"C:\....\yourvideoname.flv";

    thumbname=@"C:\...\yourjpgfilename.jpg";

    thumbargs = "-i \"" + inputfile + "\" -f image2 -vframes 1 -ss 3 -s 150x130 \"" + thumbname + "\"";

    Anonymous said...

    No errors in the code runs properly but the swf file and jpegt image is not created.
    Uploaded file is in wmv format only.
    Help me please

    Anonymous said...

    The code doesnot generate thumbnail.it uploads the same format of file which i uploaded
    what will be the issue

    Anonymous said...

    it gives me exception error

    Unknown said...

    hi i am facing some problem.
    when i am uploading the file the validation occurs says only wmv,avi and mpeg file is allowed...but my file is in avi format but uploading is not working.

    my file is
    C:\YouTube - Babbu Mann Vs Ranjit Singh and Tarsem.avi

    Kolossalservices said...

    It is good dear.
    Keep it up i m to develop a web application and it is too useful. My 80% problem is solved.

    Anonymous said...

    Hi Ramky, thanks for your coding but for me the videos are upload by me or not converting and save in the path. i need ur help and clarification.

    Thanks in advance

    Pr!nce said...

    all file is converting best also flv is converting but i found that some flv file is haveing problem to convert.

    if i upload corrupt file then proces is going on so how can we know that uploaded file is corrupt and we can give msg to user.

    Anu said...

    Great article.. very useful. The fullscreen button is not working in my pc

    Teja said...

    Hii this is teja i need little help i just want to play the videos. Which are saved in SQL Db in byte format for example streaming kind of thing in ASP Web Page please kindly help.

    chetan chaudhari said...

    Hi, can i use this code for mobile video file & how to play video on mobile?

    thnkx chetan

    chetan chaudhari said...

    Hi,
    How can i use this code to create mobile video file & How to play this video on mobile browser without HTML5?

    Anonymous said...

    Thumnail is not create.FFGEP.exe is not found.from where is it available for download.

    FiveHands said...

    hai can you give this same code in vb??

    Anonymous said...

    It's working perfectly!!!. Thank you so much for uploading such a nice work!!. I appreciate it!!

    KHAIRALLAH said...

    Thank you so much for post

    Kate said...

    Thanks for sharing.

    Unknown said...

    i am not getting any error, but the uploade video is not converting and not generating the thumbnail image.

    Anonymous said...

    when i run this code i get a error in this line proc.WaitForExit();

    error:invalid operationException was
    unhandled

    Shaik Shameer ali said...

    could you please put your process class file in your source code...

    it will be help ful..

    thanks

    ali

    Unknown said...

    Hi Ram,am bigganer to .net i want clear steps and clear codeing for how upload the video files into sqlsever and how to ply it.
    So pls give me clear codeing sir.
    thng you.

    Ramky said...

    Hey Guys,
    Please find all links related to this post....
    http://www.4shared.com/zip/f3DInGRc/VideoThumb.html
    http://www.4shared.com/rar/XGfhLsKO/VideoThumb-II.html
    http://www.4shared.com/rar/D6Wdo3ZY/ffmpeg.html

    Please note that this was developed 5 years back. You may be found new version of ffmpeg so use this code for just reference purpose...

    Ramky said...

    Hello everyone,

    Please drop your email id with the problem so that I can reply you

    Unknown said...

    im sorry Ramky for my yesterdays misbehaviour. your code worked perfectly but only by replacing a line by:
    thumbargs = "-i \"" + inputfile + "\" -f image2 -vframes 1 -ss 3 -s 150x130 \"" + thumbname + "\"";

    chinmaya parija said...

    hi ram
    when i upload a vedio
    i will find this error
    {"A 32 bit processes cannot access modules of a 64 bit process."} System.Runtime.InteropServices.ExternalException {System.ComponentModel.Win32Exception}
    please help me

    Unknown said...

    I am still not able to convert a video file to swf file.
    While I run my code, its asking me to install ffmpeg.exe.Then I install this one but no converted file available .

    Amelia Olivia said...

    Please I need a guard on how to use this ode, presently am using code behind and I need to use this code for my project. Thanks

    Rohit Kant said...

    thank u!

    Unknown said...

    Interesting one. Keep posting such kind of information on your blog. I bookmarked it and check it. Youtube Technical Support

    Unknown said...

    Hi thank you for sharing this topic. very informative.. If you are looking for Youtube Technical Support You can reach Acetecsupport at their Call Toll Free No +1-800-231-4635 For US/CA.

    Unknown said...

    Great helping Stuff...very useful...keep it Up!!!
    I am very impressed.. i think it's very helpful for us. thanks for share...Youtube Support

    Anonymous said...

    Dear please share code for saving in NAS

    Unknown said...

    Hi,

    Thanks for the article. I never knew that you tube is second largest search engine. That's something new and important to know, thanks to you! I recently brought you tube views from smmadmin.com; knowing that video marketing is very important for search engine optimization. They did it so well, that now my sales are increasing. Thanks for your article and time to read my comment.

    FILMVF STREAMING said...

    Thanks for YOur artile is helpfull ...

    FILMVF TEAM

    Anonymous said...

    Your blog is really nice and useful. Thanks Much. Please accept my post.
    Or visit my site here.
    http://quicksupportservice.com/

    Unknown said...

    Get service for Facebook related issues anytime 24*7 even at public holidays. For more information, Visit:

    www.quicksupportservice.com

    Macrosoft said...
    This comment has been removed by the author.
    Macrosoft said...

    Good details about asp.net application. This is very interesting.

    Convert ASP to ASP.Net