Java - 将音频的字节数组转换为整数数组

时间:2009-06-25 14:48:14

标签: java

我需要将音频数据作为“16位整数数组”传递到第三方系统(来自我有限的文档)。

这是我到目前为止所尝试的(系统从生成的bytes.dat文件中读取它)。

    AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File("c:\\all.wav"));
    int numBytes = inputStream.available();
    byte[] buffer = new byte[numBytes];
    inputStream.read(buffer, 0, numBytes);

    BufferedWriter fileOut = new BufferedWriter(new FileWriter(new File("c:\\temp\\bytes.dat")));

    ByteBuffer bb = ByteBuffer.wrap(buffer);

    while (bb.remaining() > 1) {
        short current = bb.getShort();
        fileOut.write(String.valueOf(current));
        fileOut.newLine();
    }

这似乎不起作用 - 第三方系统无法识别它,我也无法将文件作为原始音频导入Audacity。

有什么明显我做错了,还是有更好的方法呢?

额外信息:波形文件为16位,44100Hz,单声道。

3 个答案:

答案 0 :(得分:2)

编辑2: 我很少使用AudioInputStream,但是你写出原始数据的方式似乎相当复杂。文件只是一堆后续字节,因此您可以使用一个FileOutputStream.write()调用来编写音频字节数组。系统可能使用大端格式,而WAV文件存储在小端(?)中。然后你的音频可能会播放,但非常默默。例如。

编辑3

删除了代码示例。

您是否有理由将音频字节作为字符串写入带有换行符的文件中? 我认为系统需要二进制格式的音频数据,而不是字符串格式。

答案 1 :(得分:2)

我刚刚设法解决了这个问题。

我必须在创建ByteBuffer后添加此行。

bb.order(ByteOrder.LITTLE_ENDIAN);

答案 2 :(得分:0)

AudioFileFormat audioFileFormat;
try {
    File file = new File("path/to/wav/file");
    audioFileFormat = AudioSystem.getAudioFileFormat(file);
    int intervalMSec = 10; // 20 or 30
    byte[] buffer = new byte[160]; // 320 or 480.
    AudioInputStream audioInputStream = new AudioInputStream(new FileInputStream(file),
            audioFileFormat.getFormat(), (long) audioFileFormat.getFrameLength());
    int off = 0;
    while (audioInputStream.available() > 0) {
        audioInputStream.read(buffer, off, 160);
        off += 160;
        intervalMSec += 10;
        ByteBuffer wrap = ByteBuffer.wrap(buffer);
        int[] array = wrap.asIntBuffer().array();
    }
    audioInputStream.close();
} catch (UnsupportedAudioFileException | IOException e) {
    e.printStackTrace();
}
相关问题