This project has moved. For the latest updates, please go here.

Concatenate WAV files together brings out a file with longer duration

May 8, 2014 at 9:12 AM
Hi,

I'm a newbie for NAudio, so please be patient with me... :-)

I'm concatenating many WAV files together using the code below.
My problem is that after the operation finishes, the result WAV file has longer duration (!) than all files together...
I'm checking the duration of a WAV file
public static bool Concatenate(string outputFile, IEnumerable<string> sourceFiles, bool checkFormat)
{
    byte[] buffer = new byte[1024];
    WaveFileWriter writer = null;

    try
    {
        foreach (string sourceFile in sourceFiles)
        {
            using (WaveFileReader reader = new WaveFileReader(sourceFile))
            {
                if (writer == null)
                    writer = new WaveFileWriter(outputFile, reader.WaveFormat);
                else if (checkFormat && !reader.WaveFormat.Equals(writer.WaveFormat))
                    return false;

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

    return true;
}
I'm getting a file duration using:
public static TimeSpan GetDuration(string fileName)
{
    using (WaveFileReader wf = new WaveFileReader(fileName))
        return wf.TotalTime;
}
And I'm reading all files duration using:
public static void GetFolderTotalDuration(string folderPath, out TimeSpan totalDuration, out int countFiles)
{
    totalDuration = TimeSpan.Zero;
    countFiles = 0;
    foreach (var s in Directory.GetFiles(folderPath, "*.wav"))
    {
        countFiles++;
        totalDuration += GetDuration(s);
    }
}
What am I doing wrong? Why am I getting a longer file?
Coordinator
May 8, 2014 at 9:18 AM
you can't concatenate WAV files of different formats. That's likely the issue here. They'll not only be the wrong duration, they'll sound wrong too.
May 8, 2014 at 9:21 AM
thanks for the quick reply. please see in my code that i'm validating that all files are in the same format... this is not the issue. for sure.
Coordinator
May 8, 2014 at 9:27 AM
OK, why is there a checkFormat parameter then? That should never be false.
May 8, 2014 at 9:33 AM
the parameter is for performance. i'm using it with true.
also, i'm generating all the files with the exact wav file format...
Coordinator
May 8, 2014 at 10:33 AM
what about the Length? This is measured in bytes, and should be the same number of bytes as the total number of bytes you wrote in from each file.
May 8, 2014 at 10:47 AM
the length is different... I don't understand why. as i know, if the sample rate and bit rate are the same, than the length should be the same as well.