I am struggling to the get the length/duration of a video using FFMPEG. Below is the code which I got from Google, but when I run the method it returns empty string. Did whatever tweaks I could but no success. Can anybody please guide me what is going wrong here?
private static void GetVideoDuration()
{
string basePath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar;
string filePath = basePath + @"1.mp4";
string cmd = string.Format("-v error -select_streams v:0 -show_entries stream=duration -of default=noprint_wrappers=1:nokey=1 {0}", filePath);
Process proc = new Process();
proc.StartInfo.FileName = Path.Combine(basePath, @"ffprobe.exe");
proc.StartInfo.Arguments = cmd;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.UseShellExecute = false;
if (!proc.Start())
{
Console.WriteLine("Error starting");
return;
}
StreamReader reader = proc.StandardError;
string line;
while ((line = reader.ReadToEnd()) != null)
{
Console.WriteLine(line);
}
proc.Close();
}
Thanks everybody, I got the answer.
It seems that ffprobe does not return the output using
proc.StandardError;
but using
proc.StandardOutput;
Above statement was working fine with ffmpeg but not with ffprobe and below statement is working with ffprobe. Here is the working example in case if anybody need it.
private static void GetVideoDuration()
{
string basePath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar;
string filePath = basePath + @"1.mp4";
string cmd = string.Format("-v error -select_streams v:0 -show_entries stream=duration -sexagesimal -of default=noprint_wrappers=1:nokey=1 {0}", filePath);
Process proc = new Process();
proc.StartInfo.FileName = Path.Combine(basePath, @"ffprobe.exe");
proc.StartInfo.Arguments = cmd;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.UseShellExecute = false;
if (!proc.Start())
{
Console.WriteLine("Error starting");
return;
}
string duration = proc.StandardOutput.ReadToEnd().Replace("\r\n", "");
// Remove the milliseconds
duration = duration.Substring(0, duration.LastIndexOf("."));
proc.WaitForExit();
proc.Close();
}
Above method will return you duration in hh:mm:ss.fff tt format, means including milliseconds, but if you want duration in seconds then from command please remove the -sexagesimal.