Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a mp3 file's total time in Java?

Tags:

java

file

audio

mp3

The answers provided in How do I get a sound file’s total time in Java? work well for wav files, but not for mp3 files.

They are (given a file):

AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
AudioFormat format = audioInputStream.getFormat();
long frames = audioInputStream.getFrameLength();
double durationInSeconds = (frames+0.0) / format.getFrameRate();  

and:

AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
AudioFormat format = audioInputStream.getFormat();
long audioFileLength = file.length();
int frameSize = format.getFrameSize();
float frameRate = format.getFrameRate();
float durationInSeconds = (audioFileLength / (frameSize * frameRate));

They give the same correct result for wav files, but wrong and different results for mp3 files.

Any idea what do I have to do to get the mp3 file's duration?

like image 939
The Student Avatar asked Jun 15 '10 15:06

The Student


2 Answers

Using MP3SPI:

private static void getDurationWithMp3Spi(File file) throws UnsupportedAudioFileException, IOException {

    AudioFileFormat fileFormat = AudioSystem.getAudioFileFormat(file);
    if (fileFormat instanceof TAudioFileFormat) {
        Map<?, ?> properties = ((TAudioFileFormat) fileFormat).properties();
        String key = "duration";
        Long microseconds = (Long) properties.get(key);
        int mili = (int) (microseconds / 1000);
        int sec = (mili / 1000) % 60;
        int min = (mili / 1000) / 60;
        System.out.println("time = " + min + ":" + sec);
    } else {
        throw new UnsupportedAudioFileException();
    }

}
like image 166
The Student Avatar answered Sep 28 '22 17:09

The Student


Here is the way I get the total time of a file .mp3, I'm using the library is Jlayer 1.0.1

Header h = null;
FileInputStream file = null;
try {
    file = new FileInputStream(filename);
} catch (FileNotFoundException ex) {
    Logger.getLogger(MP3.class.getName()).log(Level.SEVERE, null, ex);
}
bitstream = new Bitstream(file);
try {
    h = bitstream.readFrame();
} catch (BitstreamException ex) {
    Logger.getLogger(MP3.class.getName()).log(Level.SEVERE, null, ex);
}
int size = h.calculate_framesize();
float ms_per_frame = h.ms_per_frame();
int maxSize = h.max_number_of_frames(10000);
float t = h.total_ms(size);
long tn = 0;
try {
    tn = file.getChannel().size();
} catch (IOException ex) {
    Logger.getLogger(MP3.class.getName()).log(Level.SEVERE, null, ex);
}
//System.out.println("Chanel: " + file.getChannel().size());
int min = h.min_number_of_frames(500);
return h.total_ms((int) tn)/1000;
like image 42
Lăng Minh Avatar answered Sep 28 '22 18:09

Lăng Minh