无法将字节数组转换为音频 AAC 文件

Unable to convert bytes array into audio AAC file

我正在努力寻找将我的字节数组写入可播放的 AAC 音频文件的解决方案。

从我的 Flutter.io 前端,我将我的 .aac 音频文件编码为 UInt8List 列表并将其发送到我的 Spring-Boot 服务器。然后我可以将它们转换为适当的字节数组,然后尝试将其写回 .aac 文件,如下所示:

public void writeToAudioFile(ArrayList<Double> audioData) {
    byte[] byteArray = new byte[1024];

    Iterator<Double> iterator = audioData.iterator();

    System.out.println(byteArray);

    while (iterator.hasNext()) {
      // for some reason my list came in as a list of doubles
      // so I am making sure to get these values back to an int
      Integer i = iterator.next().intValue();
      byteArray[i] = i.byteValue();
    }
    try {
      File someFile = new File("test.aac");
      FileOutputStream fos = new FileOutputStream(someFile);
      fos.write(byteArray);
      fos.flush();
      fos.close();

      System.out.println("File created");
    } catch (Exception e) {
      // TODO: handle exception
      System.out.println("Error: " + e);
    }

我可以将字节数组写回音频文件,但是无法播放。所以我想知道这种方法是否可行,如果我的问题确实出在 Java.

我一直在做无关的研究,我认为我需要说这个文件是一种特定类型的媒体文件?或者编码的音频文件在到达我的服务器时已损坏?

您的转化循环

while (iterator.hasNext()) {
  // for some reason my list came in as a list of doubles
  // so I am making sure to get these values back to an int
  Integer i = iterator.next().intValue();
  byteArray[i] = i.byteValue();
 }

从迭代器中获取值 i,然后尝试将其写入 byteArray 中的位置 i,这会以一种奇怪的方式混淆您的音频字节.

List<Double> 转换为 byte[] 的工作函数看起来像这样

byte[] inputToBytes(List<Double> audioData) {
  byte[] result = new byte[audioData.size()];
  for (int i = 0; i < audioData.size(); i++) {
    result[i] = audioData.get(i).byteValue();
  }
  return result;
}

那么你可以在 writeToAudioFile():

中使用它
void writeToAudioFile(ArrayList<Double> audioData) {
  try (FileOutputStream fos = new FileOutputStream("test.aac")) {
    fos.write(inputToBytes(audioData));
    System.out.println("File created");
  } catch (Exception e) {
    // TODO: handle exception
    System.out.println("Error: " + e);
  }
}

如果 audioData 中有有效字节,这肯定会生成可播放的文件。内容和扩展名应该足以让 OS/player 识别格式。

如果这不起作用,我会查看收到的数据是否正确。