如何使用Java获取声音文件的总时间中提供的答案?适用于WAV文件,但不适用于mp3文件。
它们是(给定文件):
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文件提供错误和不同的结果。
知道要获取mp3文件的持续时间该怎么办吗?
使用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();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句