如何在 Java 中获取声音文件的总时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3009908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get a sound file's total time in Java?
提问by Tom Brito
How do I get a sound file's total time in Java?
如何在 Java 中获取声音文件的总时间?
--UPDATE
- 更新
Looks like this code does de work: long audioFileLength = audioFile.length();
看起来这段代码确实有效: long audioFileLength = audioFile.length();
recordedTimeInSec = audioFileLength / (frameSize * frameRate);
I know how to get the file length, but I'm not finding how to get the sound file's frame rate and frame size... Any idea or link?
我知道如何获取文件长度,但我没有找到如何获取声音文件的帧速率和帧大小...任何想法或链接?
-- UPDATE
- 更新
One more working code (using @mdma's hints):
另一个工作代码(使用@mdma 的提示):
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));
采纳答案by mdma
Given a File
you can write
给定一个File
你可以写
File file = ...;
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(file);
AudioFormat format = audioInputStream.getFormat();
long frames = audioInputStream.getFrameLength();
double durationInSeconds = (frames+0.0) / format.getFrameRate();
回答by Milo Banks
This is a easy way:
这是一个简单的方法:
FileInputStream fileInputStream = null;
long duration = 0;
try {
fileInputStream = new FileInputStream(pathToFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
duration = Objects.requireNonNull(fileInputStream).getChannel().size() / 128;
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(duration)