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.
Related
I am trying to decompress a .s file programmatically using c#. I have tried using all the possible methods I know but couldn't decompress it. My actual file would be a file.tar.gz, I have uncompressed .tar.gz using ICSharpCode.SharpZipLib.Tar and ICSharpCode.SharpZipLib.GZip. In my uncompressed folder I would be having different files with "file_1.s" format. Can someone guide me plz?
Here is my function for decompressing:
public void ExtractTGZ(String gzArchiveName, String destFolder)
{
Stream inStream = File.OpenRead(gzArchiveName);
Stream gzipStream = new GZipInputStream(inStream);
TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream);
tarArchive.ExtractContents(destFolder);
tarArchive.Close();
gzipStream.Close();
inStream.Close();
}
public void ExtractTar(String tarFileName, String destFolder)
{
Stream inStream = File.OpenRead(tarFileName);
TarArchive tarArchive = TarArchive.CreateInputTarArchive(inStream);
tarArchive.ExtractContents(destFolder);
tarArchive.Close();
inStream.Close();
}
When a button event Occurs it will select the file.tar.gz from windows explorer and with next button it will start decompressing and its code is as shown below:
private void OpenFileLocationEvent(object sender, EventArgs e)
{
if (openLogs.ShowDialog() == DialogResult.OK)
{
tbTargetFile.Text = openLogs.FileName;
}
}
private void StartAnalysis(object sender, EventArgs e)
{
if (tbTargetFile.TextLength > 5)
{
//MessageBox.Show("Source File:" + tbTargetFile.Text + " ExtrctdDirectory:" + nextDirectory);
_uc.ExtractTGZ(tbTargetFile.Text, nextDirectory);//Extract .tar.gz
string[] files = Directory.GetFiles(nextDirectory, "*.s");
string filename = "";
string targetFile = "";
string newFile = "";
int count = 0;
foreach (string f in files)
{//Changing File Type
filename = Path.GetFileName(f);
targetFile = nextDirectory + "//" + filename;
newFile = nextDirectory + "//File_" + count + ".tar";
File.Move(targetFile, newFile);
count += 1;
//FileInfo finfo = new FileInfo(targetFile);
//finfo.MoveTo(Path.ChangeExtension(targetFile, ".txt"));
}
string[] tarfiles = Directory.GetFiles(nextDirectory, "*.tar");
foreach (string f in tarfiles)
{
filename = Path.GetFileName(f);
targetFile = nextDirectory + "\\" + filename;
MessageBox.Show("Traget File:" + targetFile + " ExtrctdDirectory:" + extrctdDirectory);
_uc.ExtractTar(targetFile, extrctdDirectory);
//_uc.ExtractTarByEntry(targetFile, extrctdDirectory, false);
//ZipFile.ExtractToDirectory(targetFile, extrctdDirectory);
}
}
}
Using a 7zip console application solved my problem. And this is my code.
private void StartAnalysis(object sender, EventArgs e)
{
if (tbTargetFile.TextLength > 5)
{
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = "7za.exe";
p.Arguments = "x \"" + tbTargetFile.Text + "\" -o\"" + nextDirectory + "\"";
p.WindowStyle = ProcessWindowStyle.Hidden;
Process x = Process.Start(p);
x.WaitForExit();
string[] files = Directory.GetFiles(nextDirectory, "*.tar");
string filename = "";
string targetFile = "";
foreach (string f in files)
{
filename = Path.GetFileName(f);
targetFile = nextDirectory + "\\" + filename;
}
p.Arguments = "x \"" + targetFile + "\" -o\"" + nextDirectory + "\"";
p.WindowStyle = ProcessWindowStyle.Hidden;
x = Process.Start(p);
x.WaitForExit();
targetFile = nextDirectory + "\\*.s";
p.Arguments = "x \"" + targetFile + "\" -o\"" + extrctdDirectory + "\"";
p.WindowStyle = ProcessWindowStyle.Hidden;
x = Process.Start(p);
x.WaitForExit();
}
}
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;
}
I want to compress a folder into a file with the .7z extension, with 7zip.
I would like to know how I would do this, because I'm not sure (which is why I'd asking.)
This is in C#.
Links to pages or sample code would be helpful.
code to zip or unzip file using 7zip
this code is used to zip a folder
public void CreateZipFolder(string sourceName, string targetName)
{
// this code use for zip a folder
sourceName = #"d:\Data Files"; // folder to be zip
targetName = #"d:\Data Files.zip"; // zip name you can change
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = #"D:\7-Zip\7z.exe";
p.Arguments = "a -t7z \"" + targetName + "\" \"" + sourceName + "\" -mx=9";
p.WindowStyle = ProcessWindowStyle.Hidden;
Process x = Process.Start(p);
x.WaitForExit();
}
this code is used to zip a file
public void CreateZip(string sourceName, string targetName)
{
// file name to be zip , you must provide file name with extension
sourceName = #"d:\ipmsg.log";
// targeted file , you can change file name
targetName = #"d:\ipmsg.zip";
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = #"D:\7-Zip\7z.exe";
p.Arguments = "a -tgzip \"" + targetName + "\" \"" + sourceName + "\" -mx=9";
p.WindowStyle = ProcessWindowStyle.Hidden;
Process x = Process.Start(p);
x.WaitForExit();
}
this code is used for unzip
public void ExtractFile(string source, string destination)
{
// If the directory doesn't exist, create it.
if (!Directory.Exists(destination))
Directory.CreateDirectory(destination);
string zPath = #"D:\7-Zip\7zG.exe";
try
{
ProcessStartInfo pro = new ProcessStartInfo();
pro.WindowStyle = ProcessWindowStyle.Hidden;
pro.FileName = zPath;
pro.Arguments = "x \"" + source + "\" -o" + destination;
Process x = Process.Start(pro);
x.WaitForExit();
}
catch (System.Exception Ex) { }
}
I agree that this is a duplicate, but I've used the demo from this codeproject before and it is very helpful:
http://www.codeproject.com/Articles/27148/C-NET-Interface-for-7-Zip-Archive-DLLs
Scroll down the page for the demo and good luck!
Here fileDirPath is the path to my folder which has all my files and preferredPath is the path where I want my .zip file to be.
eg:
var fileDirePath = #“C:\Temp”;
var prefferedPath = #“C:\Output\results.zip”;
private void CreateZipFile(string fileDirPath, string prefferedPath)
{
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = #"C:\Program Files\7-Zip\7z.exe";
p.Arguments = "a \"" + prefferedPath + "\" \"" + fileDirPath + "\"";
p.WindowStyle = ProcessWindowStyle.Hidden;
Process x = Process.Start(p);
x.WaitForExit();
return;
}
I'm starting cmd as a process in C# and I want to pass a file path in the argument. How to do it?
Process CommandStart = new Process();
CommandStart.StartInfo.UseShellExecute = true;
CommandStart.StartInfo.RedirectStandardOutput = false;
CommandStart.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
CommandStart.StartInfo.FileName = "cmd";
CommandStart.StartInfo.Arguments = "(here i want to put a file path to a executable) -arg bla -anotherArg blabla < (and here I want to put another file path)";
CommandStart.Start();
CommandStart.WaitForExit();
CommandStart.Close();
EDIT:
Process MySQLDump = new Process();
MySQLDump.StartInfo.UseShellExecute = true;
MySQLDump.StartInfo.RedirectStandardOutput = false;
MySQLDump.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
MySQLDump.StartInfo.FileName = "cmd";
MySQLDump.StartInfo.Arguments = "/c \"\"" + MySQLDumpExecutablePath + "\" -u " + SQLActions.MySQLUser + " -p" + SQLActions.MySQLPassword + " -h " + SQLActions.MySQLServer + " --port=" + SQLActions.MySQLPort + " " + SQLActions.MySQLDatabase + " \" > " + SQLActions.MySQLDatabase + "_date_" + date + ".sql";
MySQLDump.Start();
MySQLDump.WaitForExit();
MySQLDump.Close();
You need to put the file path in double quotes and use a verbatim string literal (#) as SLaks mentioned.
CommandStart.StartInfo.Arguments = #"""C:\MyPath\file.exe"" -arg bla -anotherArg";
Example with an OpenFileDialog
using(OpenFileDialog ofd = new OpenFileDialog())
{
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string filePath = "\"" + ofd.FileName + "\"";
//..set up process..
CommandStart.StartInfo.Arguments = filePath + " -arg bla -anotherArg";
}
}
Update to comment
You can format your string using String.Format.
string finalPath = String.Format("\"{0}{1}_date_{2}.sql\"", AppDomain.CurrentDomain.BaseDirectory, SQLActions.MySQLDatabase, date);
Then pass finalPath into the arguments.
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)