How to get output from ffmpeg process in c#

2019-08-27 21:34发布

问题:

In the code I written in WPF, I run some filter in FFmpeg, If I run the command in terminal (PowerShell or cmd prompt) It will give me information line by line what's going on.

I am calling the process from C# code and it's work fine. The problem I have with my code is actually I am not able to get any output from the process I run.

I have tried some answers from StackOverflow for FFmpeg process. I see 2 opportunities in my code. I can either fix it by Timer approach or secondly hook an event to OutputDataReceived.

I tried OutputDataReceived event, My code never got it worked. I tried Timer Approach but still, it's not hitting my code. Please check the code below

        _process = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = ffmpeg,
                Arguments = arguments,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true,
            },
            EnableRaisingEvents = true
        };

        _process.OutputDataReceived += Proc_OutputDataReceived;

        _process.Exited += (a, b) =>
        {
            System.Threading.Tasks.Task.Run(() =>
            {
                System.Threading.Tasks.Task.Delay(5000);
                System.IO.File.Delete(newName);
            });

            //System.IO.File.Delete()
        };

        _process.Start();
        _timer = new Timer();
        _timer.Interval = 500;
        _timer.Start();
        _timer.Tick += Timer_Tick;
    }


    private void Timer_Tick(object sender, EventArgs e)
    {
        while (_process.StandardOutput.EndOfStream)
        {
           string line = _process.StandardOutput.ReadLine();
        }
        // Check the process.

    }

回答1:

ffmpeg seems to output status updates on StandardError rather than StandardOutput.

I managed to get updates from it using the following code:

process = new Process
{
    StartInfo = new ProcessStartInfo
    {
        FileName = ffmpeg,
        Arguments = args,
        UseShellExecute = false,
        RedirectStandardOutput = true,                    
        CreateNoWindow = false,
        RedirectStandardError = true
    },
    EnableRaisingEvents = true
};

process.Start();

string processOutput = null;
while ((processOutput = process.StandardError.ReadLine()) != null)
{
    // do something with processOutput
    Debug.WriteLine(processOutput);
}