4

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

4

3 回答 3

7

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

        }
于 2010-04-26T20:32:16.680 回答
5

我尝试了接受的答案,但是在遇到异常后,我决定以简单的方式进行。

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

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

如果你有这些,你可以找出持续时间。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) { }
    }
}

希望这可以帮助那里的人!不过,我只用 WAV 文件对其进行了测试。

于 2011-06-30T20:11:15.160 回答
1

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

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

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

于 2010-04-25T20:24:03.987 回答