使用NAudio拆分Wav文件会从每个部分中删除1秒

时间:2018-02-16 12:46:43

标签: c# .net audio naudio

我正在使用NAudio将Wav文件拆分成等间隔的多个部分。我正在使用Mark Heath在Sound Code上提供的代码版本:

 public static void TrimWavFile(string inPath, string outPath, TimeSpan cutFromStart, TimeSpan cutFromEnd)
        {
            using (WaveFileReader reader = new WaveFileReader(inPath))
            {
                using (WaveFileWriter writer = new WaveFileWriter(outPath, reader.WaveFormat))
                {
                    //int bytesPerMillisecond = reader.WaveFormat.AverageBytesPerSecond / 1000;
                    float bytesPerMillisecond = reader.WaveFormat.AverageBytesPerSecond / 1000f;
                    int startPos = (int)cutFromStart.TotalMilliseconds * (int)bytesPerMillisecond;
                    startPos = startPos - startPos % reader.WaveFormat.BlockAlign;

                    int endBytes = (int)cutFromEnd.TotalMilliseconds * (int)bytesPerMillisecond;
                    endBytes = endBytes - endBytes % reader.WaveFormat.BlockAlign;
                    int endPos = (int)reader.Length - endBytes;

                    TrimWavFile(reader, writer, startPos, endPos);
                }
            }
        }

    private static void TrimWavFile(WaveFileReader reader, WaveFileWriter writer, int startPos, int endPos)
    {
        reader.Position = startPos;
        byte[] buffer = new byte[reader.WaveFormat.BlockAlign * 100];
        while (reader.Position < endPos)
        {
            int bytesRequired = (int)(endPos - reader.Position);
            if (bytesRequired > 0)
            {
                int bytesToRead = Math.Min(bytesRequired, buffer.Length);
                int bytesRead = reader.Read(buffer, 0, bytesToRead);
                if (bytesRead > 0)
                {
                    writer.Write(buffer, 0, bytesRead);
                }
            }
        }
    }

这是拆分Wav文件,但每个部分比指定的间隔短1秒。我不知道这是代码或库本身的问题。有没有人遇到同样的问题?如果是这样,有人能够解决它吗?

修改 这就是我发送给函数的内容:

    TimeSpan cutFromStart = new TimeSpan(0, 0, 0);
    TimeSpan cutFromEnd = new TimeSpan(0, 0, 0);
            cutFromEnd = totalTime.Subtract(interval);
            for (i = 0; i < numberOfParts; i++)
            {
                outPath = inpath + prefix + (i + 1).ToString() + ".wav";
                TrimWavFile(inPath, outPath, cutFromStart, cutFromEnd);
                cutFromStart = cutFromStart.Add(interval);
                cutFromEnd = cutFromEnd.Subtract(interval);

            }

1 个答案:

答案 0 :(得分:2)

我怀疑你的位置计算存在错误。

但也许你会发现使用这种技术更容易

using (var reader = new AudioFileReader(inPath))
{
    reader.CurrentTime = startTime; // jump forward to the position we want to start from
    WaveFileWriter.CreateWaveFile16(outPath, reader.Take(duration));
}