c# - 如何以编程方式将 2 个或多个 .WAV 文件连接在一起?

标签 c# audio wav

我需要能够将 2 个或更多 .wav 文件合并为一个 .wav 文件。我必须使用 C# 以编程方式执行此操作(不能选择第 3 方产品)。我知道 System.Media.SoundPlayer 类,但我不想播放 .wav,而只想创建它。

最佳答案

这是使用 NAudio 构建的基本 WAV 连接函数.这将确保只有数据 block 被连接起来(与另一个答案中链接的 this CodeProject article 中的代码示例不同)。它还可以防止您连接格式不同的 WAV 文件。

public static void Concatenate(string outputFile, IEnumerable<string> sourceFiles)
{
    byte[] buffer = new byte[1024];
    WaveFileWriter waveFileWriter = null;

    try
    {
        foreach (string sourceFile in sourceFiles)
        {
            using (WaveFileReader reader = new WaveFileReader(sourceFile))
            {
                if (waveFileWriter == null)
                {
                    // first time in create new Writer
                    waveFileWriter = new WaveFileWriter(outputFile, reader.WaveFormat);
                }
                else
                {
                    if (!reader.WaveFormat.Equals(waveFileWriter.WaveFormat))
                    {
                        throw new InvalidOperationException("Can't concatenate WAV Files that don't share the same format");
                    }
                }

                int read;
                while ((read = reader.Read(buffer, 0, buffer.Length)) > 0)
                {
                    waveFileWriter.WriteData(buffer, 0, read);
                }
            }
        }
    }
    finally
    {
        if (waveFileWriter != null)
        {
            waveFileWriter.Dispose();
        }
    }

}

关于c# - 如何以编程方式将 2 个或多个 .WAV 文件连接在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6777340/

相关文章:

c# - 如何使用 MySQL Connector/NET 在深度超过 2 的对象图上使用 Entity Framework?

c# - iOS 从本地通知打开页面

c# - 存储父子关系

python - 这是读取音频文件FFT的正确方法吗? (python + wav)

c# - 随机生成的机会非常低

objective-c - 检测音频频谱

audio - 在计算出的点或边界处提取普拉提音高(不是平均间隔音高)

audio - 我想将声音转换为数字

c# - 生成 WAV 文件铃声

audio - WAV/RIFF-文件头中的文件大小错误?