I am writing a media presentation program, and I am nearly complete, but for some reason I am getting incorrect durations of mp3 files. I use the Microsoft.DirectX.AudioVideoPlayback.Audio class to play audio files, and it works well for wav files. From google search, I can tell that it seems to be a problem when the mp3s are encoded using a variable bit rate, however I need my program to report accurately regardless of the bit rate settings of the media. Here is the code:
Media_Audio aud = (Media_Audio)item.MediaFile;
TimeSpan total = aud.EndTime - aud.StartTime;
if (aud.EndTime.TotalSeconds == 0)
{
total = TimeSpan.FromSeconds(aud.Player.Duration)-aud.StartTime;
}
TimeSpan now = TimeSpan.FromSeconds(aud.Player.CurrentPosition) - aud.StartTime;
string nows = now.Hours.ToString() + ":" + now.Minutes.ToString() + ":" + now.Seconds.ToString();
string tots = total.Hours.ToString() + ":" + total.Minutes.ToString() + ":" + total.Seconds.ToString();
item.currentPosition.Text = nows + "/" + tots;
The key line being:
total = TimeSpan.FromSeconds(aud.Player.Duration)-aud.StartTime;
aud.Player is an instance of Microsoft.DirectX.AudioVideoPlayback.Audio.
For a song that is, in fact, 5:49 seconds long, it reports 39:13 as the duration. The same length as Windows Explorer and VLC Player. Also, have the K-Lite Mega Codec pack installed. so it could be interfering. I am aware of this question: How to retrieve duration of MP3 in .NET? However, at this stage in my program I do not have the time to switch from my current method of playing audio files to a new one, so do I have any other options to determine the duration using DirectX only? Or Will I have to resort to BASS.NET or TagLib Sharp? (And does meta-data even contain accurate information for VBR-encoded mp3s?)
I wanted to post it as a comment to @anantoline, but it was too long... He is right!
Length of the VBR file CAN'T be estimated at all. Every mp3 frame inside of it could have different bitrate, so from reading any part of the file you can't know what density of the data is at any other part of the file. Only way of determining EXACT length of VBR mp3 is to DECODE it in whole, OR (if you know how) read all the headers of the frames one by one, and collect their decoded DURATION.
You will use later method only if the CPU that you use is a precious resource that you need to save. Otherwise, decode the whole file and you'll have the duration.
You can use my port of mpg123 to do the job: http://sourceforge.net/projects/mpg123net/
More: many mp3 files have "stuff" added to it, as a id3 tags, and if you don't go through all the file you could mistakenly use that tag in duration calculation.