how do i find out duration/total play time of an mp3 file using java?

3k views Asked by At

I am developing an application in Java. Part of it includes playing an mp3 file via another application. I need to find the duration (total play time) of the mp3 file. How do I do that?

2

There are 2 answers

0
Anshu kumar On

For small .mp3 files you can use:

AudioFile audioFile = AudioFileIO.read(MyFileChooser.fileName);
int duration= audioFile.getAudioHeader().getTrackLength();
System.out.println(duration);

This will give a string containing the minute and second duration in it. eg: 316 for 3:16.

Note that This method is not suitable with larger files.

0
Martin Dinov On

You can do this very easily using JAudioTagger:

Tag tag; 
java.util.logging.Logger.getLogger("org.jaudiotagger").setLevel(Level.OFF);
audioFile = AudioFileIO.read(new File(filePath));
System.out.println("Track length = " + audioFile.getAudioHeader().getTrackLength());

That will print out the track length of the file at filePath. The logger line is to remove a lot of (probably) unwanted info/debugging logging from JAudioTagger. Besides this, JAudioTagger supports getting all sorts of metadata tags from different audio file types (MP3, MP4, WMA, FLAC, Ogg Vorbis), both from file-embedded tags. You can even get MusicBrainz info easily, but I haven't tried that yet. For more info:

http://www.jthink.net/jaudiotagger/examples_read.jsp

You can get the jar files for it here:

http://download.java.net/maven/2/org/jaudiotagger/