Java中音频文件的长度

way*_*way 5 java audio mp3 audioformat

我在解析基于其字节数的mp3文件中的数据时遇到问题。

第一部分输出正确,我有一个254秒长的mp3文件,我从Github的mp3解析库mp3agic获取了它的信息。

但是,有关帧长度和持续时间的信息的第二部分是不正确的。

Length of this mp3 is: 254 seconds
Bitrate: 320 kbps (CBR)
Sample rate: 44100 Hz
Has ID3v1 tag?: NO
Has ID3v2 tag?: YES
Has custom tag?: NO

framelength -1
framerate 38.28125
duration -271265.06
Run Code Online (Sandbox Code Playgroud)

我用来获取帧长,帧率和持续时间的代码是:

File file = musicFile.getFileValue();

    this.audioStream.startMusicStream(file);

    try {
        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));

        System.out.println("framelength "+frameSize);
        System.out.println("framerate "+frameRate);
        System.out.println("duration "+durationInSeconds);

        this.setDurationLabel(durationInSeconds);
    } catch (Exception e) {
        e.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)

首先,为什么帧长和其他测量结果甚至为负?那有什么意思?以及如何使用audioinputstream和audioformat中的信息准确地计算mp3文件的持续时间?

Aaj*_*jan 0

对于帧长度和持续时间,您可以使用:

long frameLen = audioInputStream.getFrameLength();
double durationInSeconds = (frameLen+0.0) / format.getFrameRate(); 
Run Code Online (Sandbox Code Playgroud)

功能说明:

getFrameLength:Obtains the length of the stream, expressed in sample frames rather than bytes.Returns:the length in sample frames

getFrameRate:Obtains the frame rate in frames per second.Returns:the number of frames per second, or AudioSystem.NOT_SPECIFIED
Run Code Online (Sandbox Code Playgroud)

参考:

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b27/javax/sound/sampled/AudioInputStream.java#AudioInputStream.getFrameLength%28%29

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/javax/sound/sampled/AudioFormat.java#AudioFormat.getFrameRate%28%29

  • 我使用 AudioFormat format = audioInputStream.getFormat() 来获取似乎工作正常的格式对象。但是,当我调用audioInputStream.getFrameLength()时,它仍然返回-1。这导致持续时间是一个非常小的负数!问题是我从 mp3 文件获取 audioInputStream 吗?AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(文件); (3认同)