我如何在Java中的MP3文件的总时间? [英] How do I get a mp3 file's total time in Java?
本文介绍了我如何在Java中的MP3文件的总时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在提供的答案我如何在Java中得到一个声音文件的总时间?为wav文件工作得很好,但不适用于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();
和
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));
他们给同样正确的结果为wav文件,但错误的,不同的结果为MP3文件。
They give the same correct result for wav files, but wrong and different results for mp3 files.
任何想法,我必须做的就是MP3文件的时间?
Any idea what do I have to do to get the mp3 file's duration?
推荐答案
使用 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();
}
}
这篇关于我如何在Java中的MP3文件的总时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文