如何在Java中获取mp3文件的总时间?

Tom*_*ito 14 java audio mp3 file

在提供的答案如何在Java中得到一个声音文件的总时间?适用于wav文件,但不适用于mp3文件.

他们是(给定文件):

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

和:

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));
Run Code Online (Sandbox Code Playgroud)

它们为wav文件提供了相同的正确结果,但对于mp3文件却有错误和不同的结果.

知道如何获取mp3文件的持续时间?

Tom*_*ito 14

使用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();
    }

}
Run Code Online (Sandbox Code Playgroud)


小智 6

这是我获取文件 .mp3 总时间的方式,我使用的库是 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;
Run Code Online (Sandbox Code Playgroud)