你可以用这种方式学习声音文件的持续时间(这是VitalyVal的第二种方式):
import java.net.URL;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
public class SoundUtils {
public static double getLength(String path) throws Exception {
AudioInputStream stream;
stream = AudioSystem.getAudioInputStream(new URL(path));
AudioFormat format = stream.getFormat();
if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, format
.getSampleRate(), format.getSampleSizeInBits() * 2, format
.getChannels(), format.getFrameSize() * 2, format
.getFrameRate(), true); // big endian
stream = AudioSystem.getAudioInputStream(format, stream);
}
DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat(),
((int) stream.getFrameLength() * format.getFrameSize()));
Clip clip = (Clip) AudioSystem.getLine(info);
clip.close();
return clip.getBufferSize()
/ (clip.getFormat().getFrameSize() * clip.getFormat()
.getFrameRate());
}
public static void main(String[] args) {
try {
System.out
.println(getLength("..."));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试了接受的答案,但在获得例外之后,我决定以简单的方式进行。
如果您有一些基本信息,您可以计算音频数据长度。主要部分是:
如果你有这些,你可以找出持续时间。Java 很好,因为它提供了库,可以轻松地以最少的努力检索所有这些信息。方程如下:
采样率 * 样本大小 * 持续时间 * 通道数 = 文件大小
请参阅下面在 java 中执行此计算的代码:
public static double getDurationOfWavInSeconds(File file)
{
AudioInputStream stream = null;
try
{
stream = AudioSystem.getAudioInputStream(file);
AudioFormat format = stream.getFormat();
return file.length() / format.getSampleRate() / (format.getSampleSizeInBits() / 8.0) / format.getChannels();
}
catch (Exception e)
{
// log an error
return -1;
}
finally
{
try { stream.close(); } catch (Exception ex) { }
}
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助那里的人!不过,我只用 WAV 文件对其进行了测试。