lunes, 4 de abril de 2011

[C#] get the time duration of an audio file

There is a lot fo tutorials explaining how to do this, showing how thousands of codelines
will finally show you how many time will your song least, using lots of references and stuff.

I wonder why in the internet sometimes, people show us how to invent the wheel but not how to use it, of course knowing how is invented is very intresting and you should read it every time, but when you have milestones to acomplish, deliverables to finish and time is against you, you can't reinvent the wheel every time.

So the other day I came with this problem, I needed to know the audio duration of some "x" audio format, and I found tutorials on how to get it from wav files, using math formulas based on the bitrate and file size, importing windows media player, low level programming, but nothing as portable as I wanted.

Finally after lots of research, I found this amazing library:


it is openSource which is great, and also gave me the solution to my problem in 3 code lines, suporting a lot of audio formats or at least the most used/important/comercial.

if you ever want to use this codesnipet to get the audio file duration, here it is:

private static string AudioDuration(string FileFullPath) {
   TagLib.File file = TagLib.File.Create(FileFullPath);
   int s_time = (int)file.Properties.Duration.TotalSeconds;
   int s_minutes = s_time / 60;
   int s_seconds = s_time % 60;
   return s_minutes.ToString() + ":" + s_seconds.ToString() + " minutes";
}

this will get you the duration of your audio file in the format of "mm:ss minutes " of course you have to reference the library above mentioned, and use the using TagLib; reference at the top of your class.

if you dont know how to reference a library in visual studio, simply click "porject->Add reference..." in the dialog select browse and find the TagLib.dll, double click it and then click OK, and you are good to go :)

Happy coding.

1 comentario: