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();
}
}
在这里,我获得了文件的总时间.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;
here是MP3文件结构的详细说明
http://www.autohotkey.com/forum/topic29420.html
使用
jave-1.0.1.jar
图书馆
可以支持我尚未测试的视频格式。代码样本:
File source = new File("C:\\22.mp3");
Encoder encoder = new Encoder();
try {
MultimediaInfo mi = encoder.getInfo(source);
long ls = mi.getDuration();
System.out.println("duration(sec) = "+ ls/1000);
} catch (Exception e) {
e.printStackTrace();
}
Jlayer 1.0.1
jaudiotagger-2.0.3.jar
使用jlayer
学习依赖性:
implementation("javazoom:jlayer:1.0.1")
kotlin
Duration getMp3Duration(Path path) {
try {
InputStream inputStream = Files.newInputStream(path);
Header header = new Bitstream(inputStream).readFrame();
int size = (int) Files.size(path);
return Duration.ofMillis((long) header.total_ms(size));
} catch (IOException | BitstreamException e) {
return Duration.ZERO;
}
}