Calculate duration of media files such as mp3/wav programmatically using java

Programmatically get the duration of a media file using java. The file formats are limited to mp3 and wav.

1 answer

  • answered 2021-11-25 10:37 Raihanul Alam Hridoy

    After searching for long, I have found two ways to calculate duration of mp3 and wav files. For wav file:

    public static double getDurationOfWavFile(String filename){
        logger.debug("getDuration (wav) -- filename: " + filename);
        File file = null;
        double durationInSeconds=0;
        try {
            file = new File(filename);
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
            AudioFormat format = audioInputStream.getFormat();
            long frames = audioInputStream.getFrameLength();
            durationInSeconds = (frames+0.0) / format.getFrameRate();
    
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }
        return durationInSeconds;
    }
    

    Unfortunately, this method doesn't work for mp3 files. MPEG Audio Frame Header information can be seen from that URL. By performing the calculation specified in this answer, mp3 media duration can be calculated. But there is an easier way by using a java library. The library link is jlayer-1.0.1.4.jar. This library can calculate duration from a mp3 file but cannot calculate from wav file. I also tried to convert the wav file to mp3 using python script and library gtts. But it the converted mp3 fails to give correct duration. So, for wav file the above mentioned code performs best. For mp3 file the below code can be useful:

    public static float getDuration(String filename){
        logger.debug("getDuration (mp3) -- filename: " + filename);
        Bitstream bitstream;
        Header h = null;
        FileInputStream file = null;
        try {
            file = new FileInputStream(filename);
        } catch (FileNotFoundException ex) {}
        bitstream = new Bitstream(file);
        try {
            h = bitstream.readFrame();
        } catch (BitstreamException 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) {}
        int min = h.min_number_of_frames(500);
        return h.total_ms((int) tn)/1000;
    }
    

    I haven't tried any other formats. I hope this answer solves your problems.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum