.NET Questions (CLOSED)

Questions and Answers on any aspect of .NET. Now closed.

This discussion group is now closed.

Have a question about .NET development? Try stackoverflow.com, a worldwide community of great developers asking and answering questions 24 hours a day.

The archives of .NET Questions contain years of Q&A. Even older .NET Questions are still online, too.

C#: How to get the length (in seconds) of a wav file?

Hi, all.

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,
AN
Andy Nonymous
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

i.e:

time = ((total size - header size) / (sample rate * (bit rate / 8))) / number of channels
    = ((file size - 44) / (44100 * (16 / 2)) / 2)
Bennor McCarthy Send private email
Tuesday, January 22, 2008
 
 
I should add that if you do it the first way, you're still going to have to perform the calculation I gave you, the only difference is you can be sure you have the right sample rate, bit rate and number of channels.
Bennor McCarthy Send private email
Tuesday, January 22, 2008
 
 
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.
John Sibly Send private email
Friday, February 15, 2008
 
 

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics
 
Powered by FogBugz