In the uncompressed situation I know I need to read the wav header, pull out the number of channels, bits, and sample rate and work it out from there: (channels) * (bits) * (samples/s) * (seconds) = (filesize)
Is there a simpler way - a free library, or something in the .net framework perhaps?
How would I do this if the .wav file is compressed (with the mpeg codec for example)?
time = FileLength / (Sample Rate * Channels * Bits per sample /8)
What exactly is your application doing with compressed WAVs? Compressed WAV files are always tricky - I always try and use an alternative container format in this case such as OGG or WMA files. The XNA libraries tend to be designed to work with specific formats - although it is possible that within XACT you'll find a more generic wav playback method. A possible alternative is to look into the SDL C# port, although I've only ever used it to play uncompressed WAVs - once opened you can query the number of samples to determine the length.
You might find that the XNA library has some support for working with WAV's etc. if you are willing to go down that route. It is designed to work with C# for game programming, so might just take care of what you need.
Not to take anything away from the answer already accepted, but I was able to get the duration of an audio file (several different formats, including AC3, which is what I needed at the time) using the
Microsoft.DirectX.AudioVideoPlayBack
namespace. This is part of DirectX 9.0 for Managed Code. Adding a reference to that made my code as simple as this...And it's pretty fast, too! Here's a reference for the Audio class.
I'm going to assume that you're somewhat familiar with the structure of a .WAV file : it contains a WAVEFORMATEX header struct, followed by a number of other structs (or "chunks") containing various kinds of information. See Wikipedia for more info on the file format.
First, iterate through the .wav file and add up the the unpadded lengths of the "data" chunks (the "data" chunk contains the audio data for the file; usually there is only one of these, but it's possible that there could be more than one). You now have the total size, in bytes, of the audio data.
Next, get the "average bytes per second" member of the WAVEFORMATEX header struct of the file.
Finally, divide the total size of the audio data by the average bytes per second - this will give you the duration of the file, in seconds.
This works reasonably well for uncompressed and compressed files.