user2184057 user2184057 - 6 months ago 62
C# Question

Getting mp3 file length

I am currently trying to write an Audio Player in C#. I am using BASS library to deal with playing music but now i have small problem with getting length of the song.

Well i have read BASS doc and found a way:
"All" i need to do is

int stream = Bass.BASS_StreamCreateFile(filepath,....);
int length = Bass.BASS_ChannelBytes2Seconds(stream, Bass.BASS_ChannelGetLength(stream));

And in most of cases i get valid length of song. And here the problem starts. As far as i know the stream creation operation is quite expensive (correct me if i am mistaken) and creating a stream only to get length of the song looks a little silly.

So my question is: Is there any other way to get it without creating steam file (not being so expensive). I will be thinking later about reading id3 tags. Is creating that stream "evil that must be done no matter what" and even if i would try to get it with other library it would do exactly the same thing?


You can use the Microsoft.WindowsAPICodePack.Shell:

using Microsoft.WindowsAPICodePack.Shell;

Then code like so:

string file = "myfile.mp3"
ShellFile so = ShellFile.FromFilePath(file);
double nanoseconds;
double.TryParse(so.Properties.System.Media.Duration.Value.ToString(), out nanoseconds);

There is a code project that could help you as well