Naudio“TrimWavFile”功能没有正确修剪wav

时间:2014-05-10 03:38:18

标签: c# wav naudio

我被困在试图修剪wav文件。我的问题是,当我将文件(32 kbps比特率)修剪为10秒剪辑时,它会将其修剪为00:01:18。完整的原始时间是1:37:13。

我已经尝试指定CutFromStart(00:0:0:0)的值并给出CutFromEnd(00:1:37:03),但如上所述,生成的音频是01:18,因为我期待它将返回前10秒的wav剪辑...请帮助。

这是我正在使用的代码:

public static void TrimWavFile(string input, string output, TimeSpan start, TimeSpan end)
 {
 using (WaveFileReader reader = new WaveFileReader(input))
 {
   using (WaveFileWriter writer = new WaveFileWriter(output, reader.WaveFormat))
            {
                int segement = reader.WaveFormat.AverageBytesPerSecond / 1000;
                Console.WriteLine(""+segement);

                int startPosition = (int)start.TotalMilliseconds * segement;

                startPosition = startPosition - startPosition % reader.WaveFormat.BlockAlign;

                int endBytes = (int)end.TotalMilliseconds * segement;
                endBytes = endBytes - endBytes % reader.WaveFormat.BlockAlign;
                int endPosition = (int)reader.Length - endBytes;


                TrimWavFile(reader, writer, startPosition, endPosition);
            }
        }
    }

private static void TrimWavFile(WaveFileReader reader, WaveFileWriter writer, int startPosition, int endPosition)
{
   reader.Position = startPosition;
   byte[] buffer = new byte[1024];
   while (reader.Position < endPosition)
   {
      int segment = (int)(endPosition - reader.Position);
      if (segment > 0)
      {
          int bytesToRead = Math.Min(segment, buffer.Length);
          int bytesRead = reader.Read(buffer, 0, bytesToRead);
          if (bytesRead > 0)
          {
                writer.WriteData(buffer, 0, bytesRead);
          }
      }
   }
 }

1 个答案:

答案 0 :(得分:0)

从该代码的外观来看,结束并不意味着削减结束的数量,而是结束时间。所以start应该是TimeSpan.Zero,end应该是TimeSpan.FromSeconds(10)