1
votes

I am stuck in trying to trim a wav file. My problem is that when I trim the file (of 32 kbps bit rate) to a 10-second clip, it is trimming it into 00:01:18. The full, original time is 1:37:13.

I have tried specifying value of CutFromStart (00:0:0:0) and giving CutFromEnd (00:1:37:03), but as stated, the resulting audio is 01:18 where as i was expecting that it would return first 10 seconds of wav clip... Please help.

This is the code I am using:

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

1 Answers

0
votes

from the looks of that code, end doesn't mean the amount to trim off the end, but the end time. So start should be TimeSpan.Zero and end should be TimeSpan.FromSeconds(10)