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

问题描述 投票:1回答:1

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

[从前端,我将.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中列出。

我一直在进行无关紧要的研究,我认为我必须以某种方式说这是一种媒体文件。也许编码的音频文件已损坏到我的服务器。

java spring-boot audio byte audio-streaming
1个回答
0
投票

您的转换循环

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,然后尝试将其写入i中的位置byteArray,这会以一种奇怪的方式使音频字节混乱。

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中具有有效字节,则肯定会生成可播放文件。内容和扩展名应足以使操作系统/播放器识别格式。

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

© www.soinside.com 2019 - 2024. All rights reserved.