C#中如何调用指定路径的外部程序执行命令实现flac转wav
你可以通过 .NET 内置的 Process 类实现外部转换程序的调用,同时需要修正原有代码中提取输出文件名的逻辑错误,完整实现步骤如下:
1. 引入必要命名空间
在代码文件顶部添加引用:
using System.Diagnostics; using System.IO;
2. 完整实现代码
替换你原有button1_Click方法的内容:
private void button1_Click(object sender, EventArgs e) { // 固定配置可以抽成常量方便后续维护 const string ConvertExePath = @"C:\Users\Administrator\Documents\Application\convert.exe"; const string OutputDir = @"D:\WavFile\"; OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Flac file(*.flac)|*.flac"; openFileDialog.FilterIndex = 1; if (openFileDialog.ShowDialog() == DialogResult.OK) { string sourceFlacPath = openFileDialog.FileName; // 先确保输出目录存在,不存在则创建 if (!Directory.Exists(OutputDir)) { Directory.CreateDirectory(OutputDir); } // 调用外部转换程序 ProcessStartInfo processInfo = new ProcessStartInfo(); processInfo.FileName = ConvertExePath; // 源路径加双引号避免路径含空格导致命令执行错误 processInfo.Arguments = $"\"{sourceFlacPath}\" {OutputDir}"; // 不弹出命令行窗口,不需要可以删掉这两行 processInfo.CreateNoWindow = true; processInfo.UseShellExecute = false; using (Process process = Process.Start(processInfo)) { // 等待转换完成再执行后续播放逻辑,超时时间可自定义(单位毫秒) process.WaitForExit(30000); // 可选:判断转换是否成功,一般程序返回0代表执行成功 if (process.ExitCode != 0) { MessageBox.Show("音频转换失败,请检查转换程序配置"); return; } } // 修正原有文件名提取逻辑 string fileNameWithoutExt = Path.GetFileNameWithoutExtension(sourceFlacPath); string outputWavPath = Path.Combine(OutputDir, $"{fileNameWithoutExt}.wav"); // 播放转换后的wav文件 System.Media.SoundPlayer player = new SoundPlayer(); player.SoundLocation = outputWavPath; player.Play(); } }
注意事项
- 如果需要调试转换程序的执行错误,可以在
ProcessStartInfo中配置RedirectStandardError = true和RedirectStandardOutput = true,读取转换程序的输出信息排查问题 - 若转换大体积flac文件,可以适当调大
WaitForExit的超时时间,或者改为异步等待避免界面卡顿
内容的提问来源于stack exchange,提问作者Newbie10975759
相关产品推荐
相关产品推荐

