You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#调用ffmpeg添加水印时Process的DataReceived事件不触发如何解决

问题原因及修复方案

  • 未绑定ErrorDataReceived事件:ffmpeg默认将所有日志、进度信息输出到标准错误流(stderr)而非标准输出流(stdout),你当前只绑定了OutputDataReceived监听stdout,自然收不到日志。
  • 命令字符串格式错误:
    1. 路径参数未加双引号包裹,若输入路径包含空格会直接导致ffmpeg启动失败
    2. filter_complex参数的双引号未转义,实际生成的命令格式非法
  • 语法笔误:Console.Writeline拼写错误,正确写法是Console.WriteLine(L大写)
  • 进程退出后未等待异步流读取完成:直接调用Close可能会截断未处理完的输出事件

修正后代码

public void ConvertVideo(string path)
{
    // 路径加双引号避免空格问题,转义filter_complex的引号
    string command = string.Format("-i \"{0}\" -i logo.png -filter_complex \"overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2\" -c:a copy output.mp4", path);
    ProcessStartInfo oInfo = new ProcessStartInfo(@"C:\ffmpeg\ffmpeg.exe", command)
    {
        CreateNoWindow = true,
        RedirectStandardError = true,
        RedirectStandardOutput = true,
        WindowStyle = ProcessWindowStyle.Hidden,
        UseShellExecute = false,
        RedirectStandardInput = true
    };

    using Process p = new Process();
    void MyEvent(object s, DataReceivedEventArgs e)
    {
        if (!string.IsNullOrEmpty(e.Data))
        {
            Console.WriteLine(e.Data);
        }
    }

    try
    {
        // 同时绑定标准输出和标准错误的接收事件
        p.OutputDataReceived += MyEvent;
        p.ErrorDataReceived += MyEvent;
        p.StartInfo = oInfo;
        p.Start();
        // 开启两个流的异步读取
        p.BeginOutputReadLine();
        p.BeginErrorReadLine();
        p.WaitForExit(10000000);
        // 等待异步读取操作完成
        p.WaitForExit();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }
}

内容的提问来源于stack exchange,提问作者Saghar Francis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 05:24:07