I am quite new at using naudio and I am following an example provided I found on this site to trim wav files. I am using the example along with my own code to determine the lengths of wave files and trimming them to be at a length that I can use.
The program works great, it trims them perfectly everytime, exactly how I need them except for the datachunk. It is always 2 positions forward. Looking at my wav file in HxD, my original wav file datachunk is in position 37-40.
After I trim the file the datachunk is in position 39-42. This causes a problem in the other program I an using to look at the files. I have tried opening in Audacity and exporting and the datachunk position gets corrected, not sure why but it does. I have also altered the position in HxD and that works too but I would rather not have to go through all of the extra steps if I do not have to.
As I am new to naudio I am unsure if I am doing something wrong (Very possible) and I have looked for similar problems for a few days now and cannot find a single solution.
Here is the code I found through this site. The rest of my code just determines the amount that I need to trim based on the lot of files I am altering. I just read a wave file, trim and store in a different folder.
any help would be greatly appreciated, if you need any more information please let me know and I will provide what I am able to.
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;
int startPos = (int)cutFromStart.TotalMilliseconds * bytesPerMillisecond;
startPos = startPos - startPos % reader.WaveFormat.BlockAlign;
int endBytes = (int)cutFromEnd.TotalMilliseconds * 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[1024];
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.WriteData(buffer, 0, bytesRead);
}
}
}
}