Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi...

I want to know how can i get the length(duration) of a music track (with mp3 type).(for example: 3:45) in C#.

I asked this question before but no one couldn't answer it right!
If you a solution please compare it with the ex-solutions because they weren't useful !!!
and about the (.Length) I should tell the details doesn't have Length option !!!
and the ID3 doesnt give use the length it just give artist, album...!!!

:D

Thank you
Posted
Updated 13-Jan-12 1:04am
v5
Comments
Johnny J. 14-Apr-11 10:05am    
Edited for understandability

Check out this article :

http://www.codeproject.com/KB/vb/Windows_Media_Player_COM.aspx[^]

Though its in VB, you can convert it using this tool : http://www.developerfusion.com/tools/convert/vb-to-csharp/[^]
 
Share this answer
 
v2
I think you are looking for the
TagLib.File.Properties.Duration
which returns a TimeSpan object. From there you can use TotalSeconds to get the length of the mp3 in seconds.

or go through this link-
Link[^]
 
Share this answer
 
v2
Comments
Member 11587074 10-Dec-19 10:49am    
Great but the result is two or three times bigger mostly.
If the real duration is two seconds it returns 3.2 sec, or 35 sec instead of 13.
If you don't mind dealing with a Shell interop, you can use the GetDetailsOf[^] method.

Problem #1: using the Shell can be frustrating
Problem #2: the list of available file details will be different depending on the version of Windows, so you have to check for that, too.

However, this method can come in very handy, since it returns everything that it knows about the file.

Edit: A good starting example is here: http://www.codeproject.com/KB/files/detailedfileinfo.aspx[]

If you use it (or any other sample you find), increase the "i < 30" when getting the details. It's WAY above 30, now. Try 300, instead.
 
Share this answer
 
v3
Am Not Sure One of The Way
Send It to StreamReader or byte array and then find length use (.Length)
 
Share this answer
 
Comments
Johnny J. 14-Apr-11 15:24pm    
The file length in bytes haven't got much to do with the duration of the song, has it?
If you are talking about MP3 files, you want a way to read the ID3 tags. Here's a good link demonstrating this with a library written for .NET: http://stackoverflow.com/questions/68283/view-edit-id3-data-for-mp3-files[^].

Here is a general purpose media library that can be used from C# as well:
NTag[^]
 
Share this answer
 
Comments
Johnny J. 14-Apr-11 15:24pm    
Actually, Rick, I don't think he can get the length from the tag... :-)
Rick Shaub 14-Apr-11 15:58pm    
Oops. You're absolutely right.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900