FFmpeg in ASP. NET Video Conversion

Source: Internet
Author: User
Tags flv file

FFmpeg is a Linux-based tool software that is an FLV video converter that can easily convert FLV to other formats AVI, ASF, MPEG, or convert other formats to FLV. In video podcasts, we typically use it to convert our uploaded videos to FLV format to compress the video as much as possible, enabling smooth playback of video clips on existing network bandwidth. (Che Yanlu)
FFmpeg is a DOS console program, it has its own execution syntax, as long as we have its syntax function, you can use it at the command prompt to convert the corresponding video to FLV format files.
First, the grammar of FFmpeg
Example:ffmpeg-i aaa.avi-y-S 400*300-f image2-ss 0 aaa.jpg-ab 56-ar 22050-qmin 3-qmax 8-r 15-qscale 7 aaa.flv
Execution process:

"Figure 1"
Execution Result:

"Figure 2"
The parameters are many, and the parameters are not listed. Let's introduce some common parameters.
-y whether to overwrite the output file. That is, if the aaa.flv file already exists, it is overwritten without prompting.
-I "Aaa.avi" input file. You can add the path yourself
-S 400*300 the resolution size of the video file to be generated
-F image2 format to output is picture format
(Che Yanlu)
-SS 0 aaa.jpg to intercept the position of the picture, in the No. 0 second to intercept the picture, and save as aaa.jpg file
-aspect video aspect ratio 4:3 or 16:9
-vcodec xvid compressing video using XviD encoding
-acodec AAC Audio codec with AAC
-ab 56 Set the sound bitrate, set the-ac to half the bit rate when set to stereo
-AC 2 Sets the number of channels, 1 is mono, and 2 is stereo
-ar 22050 Setting the Sound sample rate
-qmin 3 Sets the minimum quality to be shared with the-qmax (set maximum mass),
-qmax 8 Sets the maximum mass, shared with-qmin (set minimum quality),
-R 15 Frame rate (can be changed to confirm that non-standard frames will cause the tone to be out of sync, so it can only be set to 15 or 29.97)
-qscale 7 7 Quality-based VBR with a value of 0.01-255, the smaller the video quality the better
aaa.flv file name of the target files
-vol 200 Audio Volume size
By ffmpeg This command we can convert AVI, ASF, MPEG and other format files into FLV video files, and generate video.

Second, call the FFmpeg command in C #
1. Execute the conversion command:
FFmpeg is an external command, in C # We need to use theProcessTo invoke the external command
//Instantiate process with a separate thread to execute the Ffmpeg.exe program
Process P = new process ();
Specifies the external command to be executed by the process, where the full path to the location of the Ffmpeg.exe is specified.
p.startinfo.filename = "Ffmpeg.exe";
Ffmpeg.exe Required Parameters when executing
p.startinfo.arguments = "-I aaa.avi-y-S 400*300-f image2-ss 0 aaa.jpg-ab 56-ar 22050-qmin 3-qmax 8-r 15-QSC Ale 7 aaa.flv ";
Do not display a black DOS window when executing the Ffmpeg.exe file
P.startinfo.createnowindow = true;
Execution thread
P.start ();
When the thread starts, it executes ffmpeg for video conversion.

2. How do I get the ffmpeg conversion progress?
It is not easy to get the FFmpeg conversion progress, because FFmpeg does not provide a way to get the conversion progress directly, we have to start the brain to achieve it. In the first picture above, we can see that a series of data is generated during the conversion process, and if we can get the data, we can resolve the conversion progress.

"Figure 3"
How to get the FFmpeg conversion progress? Process provides two eventserrordatareceivedAndoutputdatareceivedTo handle the output data during thread execution
......
Enable error output
P.startinfo.redirectstandarderror = true;
Enable standard output
P.startinfo.redirectstandardoutput = true;
handler for specifying error output
p.errordatareceived + = new Datareceivedeventhandler (p_errordatareceived);
Specify a handler for standard output
p.outputdatareceived + = new Datareceivedeventhandler (p_errordatareceived);
......
P.start ();
Read error output information
P.beginerrorreadline ();
Note: During the execution of the ffmpeg, the output data is all generated by the error output (do not know what is the reason), so we do not go from the standard output to fetch data, it is not taken out
void P_errordatareceived (object sender, Datareceivedeventargs e)
{

if (! String.IsNullOrEmpty (E.data))
{
by E. Data.tostring () to intercept strings for valid information
}
}

3. How to delete the original video file after the conversion is complete
After converting the FLV video, we should delete the original video file, which is another problem. We want to ensure that the video has been converted and then delete the original video file, or because the original video file is in use, will produce a delete exception. The process of video conversion is run as a separate thread, and we should ensure that the deletion is performed after the video conversion thread is finished, so the removal function should not be implemented in the video conversion thread, but in the main thread. (Che Yanlu)
How does the main thread know that the video conversion thread has finished executing?
We can use the exited event of the process object to implement this function. The exited event for the process object is triggered after the thread execution finishes and the resource is freed. to make this event effective, you need to set the process object's p.EnableRaisingEvents = True, if p. EnableRaisingEvents = false; The exited event is not triggered.
p.enableraisingevents = true;
p.exited + = new EventHandler (p_exited);

void P_exited (object sender, EventArgs e)
{
File.delete (Server.MapPath ("Video/bbb.avi"));
}

Iii. Reference code for video conversion using FFmpeg in ASP.
Configuration file:
<appSettings>
<add key= "Ffname" value= "FFmpeg"/>
<add key= "CVT" value= "-I aaa.avi-y-S 400*300-f image2-ss 0 aaa.jpg-ab 56-ar 22050-qmin 3-qmax 8-r 15-qscale 7 aaa.flv "/>
</appSettings>

Conversion code:(Che Yanlu)
//Read the FFmpeg command and execution parameters in the configuration file
string exe = configurationmanager.appsettings["Ffname"]. ToString ();
String str = configurationmanager.appsettings["CVT"]. ToString ();

string filename = session["name"]. ToString ();
Remove the main file name (without extension)
filename = filename. Substring (filename. LastIndexOf ("\ \") + 1, filename. LastIndexOf (".") -filename. LastIndexOf ("\ \")-1);
Change the main file name of the original aaa.avi,aaa.jpg,aaa.flv and other files to the current main file name
str = str. Replace ("Aaa.avi", Server.MapPath ("video/") +filename+ ". avi");
str = str. Replace ("Aaa.jpg", Server.MapPath ("over/image/") + filename + ". jpg");
str = str. Replace ("aaa.flv", Server.MapPath ("over/video/") + filename + ". flv");
Try
{
Process P = new process ();
p.StartInfo.FileName = Server.MapPath ("libs\\") + exe;//Specify ffmpeg command
p.startinfo.arguments = str; Specifying the FFmpeg parameter
P.startinfo.useshellexecute = false; Output information redirection
P.startinfo.createnowindow = true; Do not generate a DOS dialog box
P.startinfo.redirectstandarderror = true; REDIRECT Error output
p.errordatareceived + = new Datareceivedeventhandler (p_errordatareceived); Specify error input handler function
p.EnableRaisingEvents = true; Enable thread End Event execution
p.exited + = new EventHandler (p_exited); To specify the thread End event handler function
P.start ();
P.beginerrorreadline (); Generate data, read data
}
catch (Exception ex)
{
Response.Write (ex. Message);
}
When the page displays "over", only the current main thread is executed here, but the process P-line is impersonating is processing the video and is not finished.
Response.Write ("over");


This method is triggered when process P is released
void P_exited (object sender, EventArgs e)
{
File.delete (Server.MapPath ("Video/bbb.avi"));
}

FFmpeg The method is triggered every time a row of output data is generated
void P_errordatareceived (object sender, Datareceivedeventargs e)
{

if (! String.IsNullOrEmpty (E.data))
{
//...... Update the field in the database to identify that the video is converted and completed
}

}

FFmpeg in ASP. NET Video Conversion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.