Detecting the duration of .wav file in resources

You can use NAudio to read the resource stream and get the duration

using NAudio.Wave;
...
WaveFileReader reader = new WaveFileReader(MyProject.Resource.AudioResource);
TimeSpan span = reader.TotalTime;

You can also do what Matthew Watson suggested and simply keep the length as an additional string resource.

Also, this SO question has tons of different ways to determine duration but most of them are for files, not for streams grabbed from resources.


Ive got a way better solution for your problem, without any library. First read all bytes from the file. (optionally you can also use a FileSteam to only read the necessary bytes)

byte[] allBytes = File.ReadAllBytes(filePath);

After you got all bytes from your file, you need to get the bits per second. This value is usually stored in the bytes at indices 28-31.

int byterate = BitConverter.ToInt32(new[] { allBytes[28], allBytes[29], allBytes[30], allBytes[31] }, 0);

Now you can already get the duration in seconds.

int duration = (allBytes.Length - 8) / byterate;

Tags:

C#