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

3

我需要将音频数据作为“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,单声道。

你能多介绍一下这个第三方系统吗? - akarnokd
3个回答

3

我刚刚成功解决了这个问题。

在创建ByteBuffer后,我需要添加这一行代码。

bb.order(ByteOrder.LITTLE_ENDIAN);

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

编辑3:

已删除代码示例。

您把音频字节作为字符串写入带有换行符的文件的原因是什么?我认为系统期望以二进制格式而不是字符串格式提供音频数据。


感谢你的帮助。鉴于你提到了大/小端字节序,我已经接受了你的答案。 - William
@kd304 在使用AudioInputStream的读取方法将字节写入字节数组后,是否可以将该数组转换回音频/从该字节数组中提取音频? - Suhail Gupta

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接