Questions and Answers on any aspect of .NET. Now closed.
Using the System.Media library, I've built a dinky little program that plays wav files stored on my local machine. Is there a way to use that library (or another) to get the length, in seconds, of a given wav file?
Thanks in advance,
Tuesday, January 22, 2008
There are a couple of ways you could do it. You could manually parse the header of the file and find out the number of samples. See here for info: http://ccrma.stanford.edu/courses/422/projects/WaveFormat/
You may be able to find a library that already does this. In the past I just wrote my own.
Or, if you're only ever dealing with standard (44.1 kHz, 16-bit, stereo) wav files, you could just calculate it.
44100 samples per second with a sample size of 16 bit (or 2 bytes) is 88200 bytes per second, so if you take the file size in bytes, subtract the header size (usually 44 bytes) and then divide it by 88200, then divide that by the number of channels, you'll get the time in seconds
time = ((total size - header size) / (sample rate * (bit rate / 8))) / number of channels
= ((file size - 44) / (44100 * (16 / 2)) / 2)
If you are after a library, there is a neat little example project here: http://www.vbaccelerator.com/home/NET/Code/Media/Audio/WaveStream/article.asp
with source code in C# and VB.NET, that includes code to read the header information and calculate the wav file length. I think it only works with uncompressed wav files.
This topic is archived. No further replies will be accepted.Other recent topics
Powered by FogBugz