Java中的音频文件长度

我在解决基于它的字节的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

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

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();
    }

所有的拳头,为什么帧长和其他测量甚至是负的?那有什么意思?如何使用audioinputstream和audioformat中的信息准确计算mp3文件的持续时间?

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

long frameLen = audioInputStream.getFrameLength();
double durationInSeconds = (frameLen+0.0) / format.getFrameRate(); 

功能说明:

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

参考文献:

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

点赞