Search code examples
c#ffprobe

Use C# and FFProbe to get bit rate of a video but it returns null for some reason


I tried to use FFProbe to get video bit rate data from a video file in C#. However, the string it returned before I could parse it into an integer was for some reason, null. This made the int.Parse to throw a NullReferenceException. Here was the function I wrote to get bit rate:

    private float GetBitrate() {
        string command = $"ffprobe -v quiet -select_streams v:0 -show_entries format=bit_rate -of default=noprint_wrappers=1 \"{sourceField.text}\"";
        string result = null;
        using (var p = new Process()) {
            p.StartInfo.FileName = ffprobePath;
            p.StartInfo.Arguments = command;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.OutputDataReceived += (s, e) => result = e.Data;
            p.ErrorDataReceived += (s, e) => throw new ArgumentException(e.Data);
            p.Start();
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
            p.WaitForExit();
        }
        int value = int.Parse(result.Replace("bit_rate=", string.Empty).Trim());
        return (float)value / 1000;
    }

I tested the command in cmd and it worked. I did not know why it could not work in the code. Can anyone tell me if there is anything done wrong here?


Solution

  • I cleaned up your code a bit. Basically the line

    string command = $"ffprobe -v quiet -select_streams v:0 -show_entries format=bit_rate -of default=noprint_wrappers=1 \"{sourceField.text}\"";

    is not quite right.

    You are passing ffprobe as argument to ffprobe.

    Here the code

     float GetBitrate(string filePath) {
            var command = $"-v quiet -select_streams v:0 -show_entries format=bit_rate -of default=noprint_wrappers=1 {filePath}";
            using var p = new Process();
            p.StartInfo.FileName = "ffprobe";
            p.StartInfo.Arguments = command;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            //p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardOutput = true;
            
            p.Start();
            p.WaitForExit();
            var result = p.StandardOutput.ReadToEnd();
            int value = int.Parse(result.Replace("bit_rate=", string.Empty).Trim());
            return (float)value / 1000;
      }