You need to enable JavaScript to run this app. C#中如何调用指定路径的外部程序执行命令实现flac转wav
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 12:18:00