使用 java 以编程方式计算 mp3/wav 等媒体文件的持续时间

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

使用 java 以编程方式获取媒体文件的持续时间。文件格式仅限于 mp3wav.

找了很久,找到了两种计算mp3和wav文件时长的方法。 对于 wav 文件:

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;
}

很遗憾,此方法不适用于 mp3 文件。 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。这个库可以从 mp3 文件计算持续时间,但不能从 wav 文件计算。我还尝试使用 python 脚本和库 gtts 将 wav 文件转换为 mp3。但是转换后的 mp3 无法给出正确的持续时间。因此,对于 wav 文件,上述代码执行得最好。对于 mp3 文件,以下代码可能很有用:

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;
}

我还没有尝试过任何其他格式。希望这个回答能解决您的问题。