4

I need to create a M3U playlist of mp3 songs.

Is there any way to read the duration attribute of MP3 files?

Alex Butenko
  • 3,664
  • 3
  • 35
  • 54
BIKTOP
  • 123
  • 1
  • 2
  • 7
  • Possible duplicate of [How to read metadata from mp3?](http://stackoverflow.com/questions/11369719/how-to-read-metadata-from-mp3) – Jonathon Chase Dec 29 '15 at 19:28
  • 4
    Are we here to google for you or have you actually researched and tried something on your own? In case you don't know about [this site](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=mp3%20c%23%20duration). – Rick S Dec 29 '15 at 19:28
  • `Is there any way to read the duration attribute of MP3 files?` **Yes!** – Ňɏssa Pøngjǣrdenlarp Dec 29 '15 at 19:30
  • 2
    Possible duplicate of [How to retrieve duration of MP3 in .NET?](http://stackoverflow.com/questions/383164/how-to-retrieve-duration-of-mp3-in-net) – David Culp Dec 29 '15 at 19:59

2 Answers2

14

Don't reinvent the wheel. Use an external library such as NAudio to do the hard work.

  • NAudio is available at GitHub.

You can use it like this:

Mp3FileReader reader = new Mp3FileReader("<YourMP3>.mp3");
TimeSpan duration = reader.TotalTime;

Of course, an alternative would be this answer.

To use the Mp3FileReader class, you must add using NAudio.Wave; to your file.

zChris128
  • 25
  • 6
Fᴀʀʜᴀɴ Aɴᴀᴍ
  • 6,131
  • 5
  • 31
  • 52
5

Thanks everyone for help.

I tryed using TagLib and it works fine.

TagLib.File f = TagLib.File.Create(<pathToFile>, TagLib.ReadStyle.Average);
var duration = (int)f.Properties.Duration.TotalSeconds;
BIKTOP
  • 123
  • 1
  • 2
  • 7
  • 4
    There is a bug with TagLib's duration properties. Most of the cases the actual time is only 70% of the taglibs duration – StartCoding Jun 11 '17 at 08:35
  • @StartCoding ~ Thanks for the warning. I decided to use `NReco.VideoInfo` instead. It wraps `ffprobe` from the `ffmpeg` toolbox. If one is doing much work with videos, `ffmpeg` is already in one's system path. – InteXX Mar 18 '19 at 15:36