从同一音频文件中获取不同的字节

时间:2016-12-20 13:50:17

标签: java audio-streaming

我正在尝试将音频文件转换为标准格式并读取字节。

我做的第一件事是:

static void main(String [] args)
{
    File file = new File("/path/to/my/file.mp3");
    AudioInputStream source = AudioSystem.getAudioInputStream(file);
    AudioFormat sourceFormat = source.getFormat();

    AudioFormat convertFormat = new AudioFormat(
                AudioFormat.Encoding.PCM_SIGNED,
                sourceFormat.getSampleRate(),
                16,
                sourceFormat.getChannels(),
                sourceFormat.getChannels() * 2,
                sourceFormat.getSampleRate(),
                false);
    AudioInputStream convert1AIS = AudioSystem.getAudioInputStream(convertFormat, source);

    AudioFormat targetFormat = new AudioFormat(
            44100,
            8,
            1,
            true,
            true);

    AudioInputStream target = AudioSystem.getAudioInputStream(targetFormat, convert1AIS);

    byte[] buffer = new byte[4096];


    //Here come strange things
    target.read(buffer,0, buffer.length);


}

每次启动程序时,缓冲区都包含不同的字节,即前10个字节,我在调试器中看到的字节永远不会相同。怎么了?

我添加了以下库: jl1.0.1.jar, jtransform-2.4.jar, mp3spi1.9.5.jar, tritonus_remaining-0.3.6.jar, tritonus_share.jar

OS。 Ubuntu 14.04

java版“1.8.0_111” Java(TM)SE运行时环境(版本1.8.0_111-b14) Java HotSpot(TM)64位服务器VM(版本25.111-b14,混合模式)

1 个答案:

答案 0 :(得分:0)

核心问题是: 保证对 read 的调用始终会从输入中读取完全相同的字节数。

相反,read方法返回读回给您的字节数。所以你总是需要一个循环来继续阅读,直到所有预期的字节真正被读取为止!

编辑:给出您的意见:您正在此处进行音频转化;所以我的猜测是:这个过程根本不是确定性的。换句话说:该MP3文件的实际输入字节将始终相同;但是你的代码会对其进行转换;如上所述;那些转变是非确定性的;因此每次运行都会产生略微不同的结果。

相关问题