如何在Java媒体框架中学习.wav持续时间?

我想使用java媒体框架将.mov文件与.wav文件合并,因此我需要知道它们的持续时间。 我怎样才能做到这一点? 任何想法,将不胜感激..

你可以用这种方式学习声音文件的持续时间(这是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(); } } } 

我尝试了接受的答案,但在得到它的例外后,我决定以简单的方式做到这一点。

如果您有一些基本信息,则可以计算音频数据长度。 主要部分是:

  • 采样率
  • 样本量(每个样本的位数)
  • 文件大小
  • 通道数量(单声道/立体声)

如果你有这些,你可以找出持续时间。 Java很不错,因为它提供了库,可以轻松地轻松检索所有这些信息。 公式如下:

采样率*样本大小*持续时间* channel-count =文件大小

请参阅以下在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) { } } } 

希望这有助于那里的人! 不过,我只用WAV文件测试过它。

我不熟悉java媒体框架,但以下内容可能会有所帮助:

1)从理论上讲,你可以从“事实”块中获取wav文件的持续时间。 但我怀疑,JMF可以直接访问大块。 此外,块可能包含不正确的值。

2)您可以计算持续时间,知道音频数据大小(以字节为单位)和采样率(或比特率)。