Merge videos in c# asp.net using ffmpeg - c#

Is it possible to merge the two videos by c# asp.net with the help of ffmpeg. In the ffmpeg documentation they gave us cat command. But it wont works in asp.net. I thought it only for linux.
cat intermediate1.mpg intermediate2.mpg > intermediate_all.mpg
asp.net execute this command but there is no output. Help me.
namespace demo
{
public partial class Default : System.Web.UI.Page
{
protected void Button2_Click(object sender, EventArgs e)
{
string strFile = "cars1.flv";
MergeFiles(strFile);
}
public void MergeFiles(string strFile)
{
string strParam;
string Path_FFMPEG = Server.MapPath("~/ffmpeg/bin/ffmpeg.exe");
//Converting a video into mp4 format
string strOrginal = Server.MapPath("~/Videos/");
strOrginal = strOrginal + strFile;
string strConvert = Server.MapPath("~/Videos/ConvertedFiles/");
string strExtn = Path.GetExtension(strOrginal);
if (strExtn != ".mp4")
{
strConvert = strConvert + strFile.Replace(strExtn, ".mp4");
strParam = "-i " + strOrginal + " " + strConvert;
//strParam = "-i " + strOrginal + " -same_quant " + strConvert;
process(Path_FFMPEG, strParam);
}
//Merging two videos
String video1 = Server.MapPath("~/Videos/Cars1.mp4");
String video2 = Server.MapPath("~/Videos/ConvertedFiles/Cars2.mp4");
String strResult = Server.MapPath("~/Videos/ConvertedFiles/Merge.mp4");
//strParam = "-loop_input -shortest -y -i " + video1 + " -i " + video2 + " -acodec copy -vcodec mjpeg " + strResult;
strParam = " -i " + video1 + " -i " + video2 + " -acodec copy -vcodec mjpeg " + strResult;
process(Path_FFMPEG, strParam);
}
public void process(string Path_FFMPEG, string strParam)
{
try
{
Process ffmpeg = new Process();
ProcessStartInfo ffmpeg_StartInfo = new ProcessStartInfo(Path_FFMPEG, strParam);
ffmpeg_StartInfo.UseShellExecute = false;
ffmpeg_StartInfo.RedirectStandardError = true;
ffmpeg_StartInfo.RedirectStandardOutput = true;
ffmpeg.StartInfo = ffmpeg_StartInfo;
ffmpeg_StartInfo.CreateNoWindow = true;
ffmpeg.EnableRaisingEvents = true;
ffmpeg.Start();
ffmpeg.WaitForExit();
ffmpeg.Close();
ffmpeg.Dispose();
ffmpeg = null;
}
catch (Exception ex)
{
}
}
}
}

Finally i found the answer for my own question.
The following method resolves my problem.
public void MergeFiles(string strFile)
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = Server.MapPath("~/app.bat");
p.Start();
p.WaitForExit();
p.Dispose();
}
app.bat
The app.bat contains the following code.
copy e:\cars1.mpg /b + e:\cars2.mpg /b e:\output.mpg /b
NOTE: This is for windows only. That's why "cat" command doesn't works. Instead of "cat" command we use copy command.

Creating app. Bat file double the file size but it play as single. Still problem not resolved. You should try ffmpeg concat command approach in which you need to create a text file that contain files names and this file should be on same folder where mp4 file are. the below code will help you i was facing the same issue. My task was to merge two mp4 files and I merge successfully when I was doing it from Command prompt. But stuck when I was doiing it through asp. Net. My issue resolved by given correct path and remove ffmpeg from command. For E. G( ffmepg - f concat TO - f concat)
Dim _ffmpeg As String = "D:\Develop\Experiment\mergermp4Vb\mergermp4Vb\bin\ffmpeg.exe"
Dim params = "-f concat -i D:\Develop\Experiment\mergermp4Vb\mergermp4Vb\Videos\mylist2.txt -c copy D:\Develop\Experiment\mergermp4Vb\mergermp4Vb\Videos\0104.mp4"
Dim _FFmpegProcessPropertys As New ProcessStartInfo
_FFmpegProcessPropertys.FileName = _ffmpeg
_FFmpegProcessPropertys.Arguments = params
_FFmpegProcessPropertys.UseShellExecute = False
_FFmpegProcessPropertys.RedirectStandardOutput = True
_FFmpegProcessPropertys.RedirectStandardError = True
_FFmpegProcessPropertys.CreateNoWindow = True
Dim FFmpegProcess = Process.Start(_FFmpegProcessPropertys)

Related

Place two videos side by side using ffmpeg?and download it as one file

I have two video files, which I want to play side by side and download them later. I used FFMPEG to merge them as one:
protected void combinetwovideo()
{
string strParam;
string Path_FFMPEG = Path.Combine(HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["FFMpegPath"]));
string apppath=HttpRuntime.AppDomainAppPath;
//Merging two videos
String video1=apppath+"\\recordings\\client2019-08-03 02_23_59";
String video2 =apppath+"\\userrecord\\User2019-08-03 02_24_00";
String strResult =apppath+"\\RESULT\\";
strParam = string.Format("-i ('" + video1 + "') -i ('" + video2 + "') -filter_complex \'[0:v]pad=iw*2:ih[int];[int][1:v]overlay=W/2:0[vid]' /-map [vid] -c:v libx264 -crf 23 -preset veryfast output.mp4");
process(Path_FFMPEG, strParam);
}
public void process(string Path_FFMPEG, string strParam)
{
try
{
Process ffmpeg = new Process();
ProcessStartInfo ffmpeg_StartInfo = new ProcessStartInfo(Path_FFMPEG, strParam);
ffmpeg_StartInfo.UseShellExecute = false;
ffmpeg_StartInfo.RedirectStandardError = true;
ffmpeg_StartInfo.RedirectStandardOutput = true;
ffmpeg.StartInfo = ffmpeg_StartInfo;
ffmpeg_StartInfo.CreateNoWindow = true;
ffmpeg.EnableRaisingEvents = true;
ffmpeg.Start();
ffmpeg.WaitForExit();
ffmpeg.Close();
ffmpeg.Dispose();
ffmpeg = null;
}
catch (Exception ex)
{
}
}
But this method outputs nothing and does not throw any errors. I'm confused about the strParam query. Did I write it wrong or am I missing something. Any help would be apreciated.

concatenate two videos using ffmpeg.

string strParam;
string Path_FFMPEG = #"C:\Windows\system32\cmd.exe";
string WorkingDirectory = #"C:\Users\Braintech\documents\visual studio 2013\Projects\convertVideo\convertVideo";
string command1 = "ffmpeg -i video1.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts intermediate1.ts";
string command2 = "ffmpeg -i video2.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts intermediate1.ts";
string command3 = "ffmpeg -i" + "concat:intermediate1.ts|intermediate2.ts" + " -c copy -bsf:a aac_adtstoasc Output.mp4";
string Command = #"" + command1 + " & " + command2 + " & " + command3 + " ";
strParam = "ffmpeg -f concat -i " + file + " -c copy " + strResult;
process(Path_FFMPEG, Command, WorkingDirectory);
public static void process(string Path_FFMPEG, string Command, string WorkingDirectory)
{
try
{
Process ffmpeg = new Process();
ProcessStartInfo ffmpeg_StartInfo = new ProcessStartInfo(Path_FFMPEG, Command);
ffmpeg_StartInfo.WorkingDirectory = WorkingDirectory;
ffmpeg_StartInfo.UseShellExecute = false;
ffmpeg_StartInfo.RedirectStandardError = true;
ffmpeg_StartInfo.RedirectStandardOutput = true;
ffmpeg.StartInfo = ffmpeg_StartInfo;
ffmpeg_StartInfo.CreateNoWindow = true;
ffmpeg.EnableRaisingEvents = true;
ffmpeg.Start();
ffmpeg.WaitForExit(30000);
ffmpeg.Close();
ffmpeg.Dispose();
ffmpeg = null;
}
catch (Exception ex)
{
}
}
I m trying to merge two video using ffmpeg. But it is working manually but not able to execute using c# code.it works when i run the command on cmd manually. But when i am trying to run using c# it not works.Please help someone.
Thanks in advance.
Basically, don't try to load it into an array. For large files, you should have a range of overloads of the File() method that take a path or Stream, and know what to do. For example:
return File("/TestVideo/Wildlife.wmv", "video/x-ms-wmv");
or:
return File(videoPath, "video/x-ms-wmv");
However, video is really a special case and may benefit from more specialized handling.
Returning the byte array is really a NO-go.So, instead of returning the whole video as a byte array, why not saving it somewhere (ex. your Web API), if it's not already saved as a file, and send the video URI back as the response?
The video player you are going to use will for sure know how to handle that URI.
Another option is to enable 206 PARTIAL CONTENT support in your Web API and use the URI of your Web API in your video player.
See here https://stackoverflow.com/a/33634614/2528907
issue is with the path. you should give file path in your Commands
may be the below code will help
in which the mylist.txt file contain
file '01.mp4'
file '04.mp4'
Dim _ffmpeg As String = "D:\Develop\Experiment\mergermp4Vb\mergermp4Vb\Videos\ffmpeg.exe"
Dim params = "-f concat -i D:\Develop\Experiment\mergermp4Vb\mergermp4Vb\Videos\mylist2.txt -c copy D:\Develop\Experiment\mergermp4Vb\mergermp4Vb\Videos\0104.mp4"
Dim _FFmpegProcessPropertys As New ProcessStartInfo
_FFmpegProcessPropertys.FileName = _ffmpeg
_FFmpegProcessPropertys.Arguments = params
_FFmpegProcessPropertys.UseShellExecute = False
_FFmpegProcessPropertys.RedirectStandardOutput = True
_FFmpegProcessPropertys.RedirectStandardError = True
_FFmpegProcessPropertys.CreateNoWindow = True
Dim FFmpegProcess = Process.Start(_FFmpegProcessPropertys)

C# + 7z.exe doesn't seem to work [duplicate]

This question already has answers here:
Unzip a file in c# using 7z.exe
(6 answers)
Closed 8 years ago.
string path = #"C:\Users\<user>\Documents\Visual Studio\Projects\7ZipFile\RequiredDocs\";
ProcessStartInfo zipper = new ProcessStartInfo(#"C:\Program Files\7-Zip\7z.exe");
zipper.Arguments = string.Format("a -t7z {0}.7z {0} *.txt -mx9", path);
zipper.RedirectStandardInput = true;
zipper.UseShellExecute = false;
zipper.CreateNoWindow = true;
zipper.WindowStyle = ProcessWindowStyle.Hidden;
Process process = Process.Start(zipper);
Goal: Zip all *.txt file(s) within "path" and save that zipped file within "path" and these .txt files should not be present in the "path" after zipping
When I run the code, nothing seems to happen (0 error)...
Please help!
Thank you
UPDATE: I am using 7Zip and have installed 7Zip application on Windows where this code will be used w/ .NET 3.5.
The normal way of using 7Zip from a program is to invoke 7za.exe (not the installed 7z program) and include 7za with your application.
This page has a good tutorial on how to use it. Works great every time I have needed to zip/7zip programmatically.
You could also use the ZipArchive class if you want normal zip functionality in a pure .NET way (requires .NET 4.5)
Also, your path should be in quotes in case there is a space. Note that the quotes are escaped with '\'. "" is also a valid escape sequence for a quote in C#:
string.Format("a -t7z \"{0}.7z\" \"{0}\" *.txt -mx9", path);
Here's an example from my application. This example extracts an archive but it shows you how to set up the process. Just change the command to 7z and the arguments. This example assumes you're shipping 7za.exe with your application. Good luck.
public static bool ExtractArchive(string f) {
string tempDir = Environment.ExpandEnvironmentVariables(Configuration.ConfigParam("TEMP_DIR"));
if (zipToolPath == null) return false;
// Let them know what we're doing.
Console.WriteLine("Unpacking '" + System.IO.Path.GetFileName(f) + "' to temp directory.");
LogFile.LogDebug("Unpacking '" + System.IO.Path.GetFileName(f) + "' to temp directory '" + tempDir + "'.",
System.IO.Path.GetFileName(f));
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
if (pid == PlatformID.Win32NT || pid == PlatformID.Win32S || pid == PlatformID.Win32Windows || pid == PlatformID.WinCE) {
p.StartInfo.FileName = "\"" + Path.Combine(zipToolPath, zipToolName) + "\"";
p.StartInfo.Arguments = " e " + "-y -o" + tempDir + " \"" + f + "\"";
} else {
p.StartInfo.FileName = Path.Combine(zipToolPath, zipToolName);
p.StartInfo.Arguments = " e " + "-y -o" + tempDir + " " + f;
}
try {
p.Start();
} catch (Exception e) {
Console.WriteLine("Failed to extract the archive '" + f + "'.");
LogFile.LogError("Exception occurred while attempting to list files in the archive.");
LogFile.LogExceptionAndExit(e);
}
string o = p.StandardOutput.ReadToEnd();
p.WaitForExit();
string[] ls = o.Split('\n');
for (int i = 0; i < ls.Count(); i++) {
string l = ls[i].TrimEnd('\r');
if (l.StartsWith("Error")) {
LogFile.LogError("7za: Error '" + ls[i + 1] + "'.", f);
Console.WriteLine("Failed to extract the archive '" + f + "'.");
return false;
}
}
return true;
}

Upload any video and convert to .mp4 online in .net

I have a strange requirement. User can upload their video of any format (or a limited format). We have to store them and convert them to .mp4 format so we can play that in our site.
Same requirement also for audio files.
I have googled but I can't get any proper idea. Any help or suggestions....??
Thanks in advance
You can convert almost any video/audio user files to mp4/mp3 with FFMpeg command line utility. From .NET it can be called using wrapper library like Video Converter for .NET (this one is nice because everything is packed into one DLL):
(new NReco.VideoConverter.FFMpegConverter()).ConvertMedia(pathToVideoFile, pathToOutputMp4File, Formats.mp4)
Note that video conversion requires significant CPU resources; it's good idea to run it in background.
Your Answer
please Replace .flv to .mp4 you will get your answer
private bool ReturnVideo(string fileName)
{
string html = string.Empty;
//rename if file already exists
int j = 0;
string AppPath;
string inputPath;
string outputPath;
string imgpath;
AppPath = Request.PhysicalApplicationPath;
//Get the application path
inputPath = AppPath + "OriginalVideo";
//Path of the original file
outputPath = AppPath + "ConvertVideo";
//Path of the converted file
imgpath = AppPath + "Thumbs";
//Path of the preview file
string filepath = Server.MapPath("~/OriginalVideo/" + fileName);
while (File.Exists(filepath))
{
j = j + 1;
int dotPos = fileName.LastIndexOf(".");
string namewithoutext = fileName.Substring(0, dotPos);
string ext = fileName.Substring(dotPos + 1);
fileName = namewithoutext + j + "." + ext;
filepath = Server.MapPath("~/OriginalVideo/" + fileName);
}
try
{
this.fileuploadImageVideo.SaveAs(filepath);
}
catch
{
return false;
}
string outPutFile;
outPutFile = "~/OriginalVideo/" + fileName;
int i = this.fileuploadImageVideo.PostedFile.ContentLength;
System.IO.FileInfo a = new System.IO.FileInfo(Server.MapPath(outPutFile));
while (a.Exists == false)
{
}
long b = a.Length;
while (i != b)
{
}
string cmd = " -i \"" + inputPath + "\\" + fileName + "\" \"" + outputPath + "\\" + fileName.Remove(fileName.IndexOf(".")) + ".flv" + "\"";
ConvertNow(cmd);
string imgargs = " -i \"" + outputPath + "\\" + fileName.Remove(fileName.IndexOf(".")) + ".flv" + "\" -f image2 -ss 1 -vframes 1 -s 280x200 -an \"" + imgpath + "\\" + fileName.Remove(fileName.IndexOf(".")) + ".jpg" + "\"";
ConvertNow(imgargs);
return true;
}
private void ConvertNow(string cmd)
{
string exepath;
string AppPath = Request.PhysicalApplicationPath;
//Get the application path
exepath = AppPath + "ffmpeg.exe";
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = exepath;
//Path of exe that will be executed, only for "filebuffer" it will be "flvtool2.exe"
proc.StartInfo.Arguments = cmd;
//The command which will be executed
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = false;
proc.Start();
while (proc.HasExited == false)
{
}
}
protected void btn_Submit_Click(object sender, EventArgs e)
{
ReturnVideo(this.fileuploadImageVideo.FileName.ToString());
}
I know it's a bit old thread but if I get here other people see this too. You shoudn't use it process info to start ffmpeg. It is a lot to do with it. Xabe.FFmpeg you could do this by running just
await Conversion.Convert("inputfile.mkv", "file.mp4").Start()
This is one of easiest usage. This library provide fluent API to FFmpeg.

How to capture thumbnail for video while uploading it in ASP.NET?

I want to know how to capture thumbnail for video while uploading it in ASP.NET ?
Well first of all, you will also need to convert it to MP4 which will work on everywhere. For that you can use ffmpeg tool,
To Create Thumbnail,
//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();
However, for more details about the code, see this link.
http://ramcrishna.blogspot.com/2008/09/playing-videos-like-youtube-and.html
And you will need to change paths according to your web application's path.

Categories