在C#应用中获取qaac转AAC格式的转换进度问题
解决C#中获取qaac转换AAC进度的问题
问题背景
使用qaac库将音视频轨道转换为AAC格式时,CMD中可正常显示转换进度,但在C#应用中,虽转换功能正常,却无法获取进度信息:OutputDataReceived事件的received.Data始终为null,ErrorDataReceived事件也无法捕获有效进度数据。选择qaac是因为ffmpeg转换AAC时存在结果轨道时长错误的问题,暂未找到解决办法。
问题原因
- 未重定向标准错误流:qaac默认将进度信息输出到标准错误流(stderr),但原代码的
ProcessStartInfo未设置RedirectStandardError = true,导致ErrorDataReceived事件无法捕获到进度数据。 - 标准输出流无进度数据:qaac的标准输出流(stdout)仅在特定模式下(如
-stdout参数)输出音频数据,不会输出进度信息,因此OutputDataReceived事件自然拿不到数据。
解决步骤
1. 修改进程启动配置
更新ProcessStartInfo,添加标准错误流重定向:
string arguments = $"\"{engineParameters.InputFile.Filename}\" -no-delay -o \"{engineParameters.OutputFile.Filename}\""; processStartInfo = new ProcessStartInfo { FileName = QaacFilePath, Arguments = arguments, RedirectStandardOutput = true, RedirectStandardError = true, // 关键:开启错误流重定向 UseShellExecute = false, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden };
2. 解析ErrorDataReceived事件中的进度数据
qaac的进度信息格式通常为Encoding 12345/67890 samples (18%)这类字符串,可通过正则提取百分比:
this.Process.ErrorDataReceived += (sender, received) => { if (string.IsNullOrEmpty(received.Data)) return; // 匹配进度百分比的正则表达式 var match = System.Text.RegularExpressions.Regex.Match(received.Data, @"\((\d+)%\)"); if (match.Success) { int progress = int.Parse(match.Groups[1].Value); // 此处更新UI或处理进度逻辑,跨线程操作需使用Invoke // 示例:this.Invoke(new Action(() => progressBar.Value = progress)); } };
3. 确保进程调用顺序正确
启动进程后再调用异步读取方法,避免逻辑顺序错误:
this.Process.Start(); this.Process.BeginOutputReadLine(); this.Process.BeginErrorReadLine(); this.Process.WaitForExit();
额外说明
- qaac的进度输出采用动态刷新(用
\r覆盖当前行),ErrorDataReceived可能收到重复或截断的字符串,正则匹配需具备容错性。 - 若需更详细的编码信息,可添加qaac的
--verbose参数,再针对性解析数据。
内容的提问来源于stack exchange,提问作者Alex1347
相关产品推荐
相关产品推荐

