【问题标题】:Converting array with samples into byte array将带有样本的数组转换为字节数组
【发布时间】:2011-09-14 20:17:17
【问题描述】:

我有二维整数数组。第一个索引表示通道数。第二个表示通道中的样本数。如何将此数组保存到音频文件中?我知道,我必须将它转换为字节数组,但我不知道该怎么做。

// 编辑

更多信息。我已经有一个绘制波形的类。在这里:

http://javafaq.nu/java-example-code-716.html

现在我想剪掉这波的一部分并将其保存到新文件中。所以我要切掉一部分int[][] samplesContainer,把它转换成字节数组(我不知道怎么做),然后保存到和audioInputStream格式相同的文件中。

// 编辑

好的。所以最大的问题是给这个写倒函数:

protected int[][] getSampleArray(byte[] eightBitByteArray) {
int[][] toReturn = new int[getNumberOfChannels()][eightBitByteArray.length / (2 * getNumberOfChannels())];
int index = 0;
    //loop through the byte[]
    for (int t = 0; t < eightBitByteArray.length;) {
        //for each iteration, loop through the channels
        for (int a = 0; a < getNumberOfChannels(); a++) {
            //do the byte to sample conversion
            //see AmplitudeEditor for more info
            int low = (int) eightBitByteArray[t];
            t++;
            int high = (int) eightBitByteArray[t];
            t++;
            int sample = (high << 8) + (low & 0x00ff);

            if (sample < sampleMin) {
                sampleMin = sample;
            } else if (sample > sampleMax) {
                sampleMax = sample;
            }
            //set the value.
        toReturn[a][index] = sample;
        }
        index++;
        }
    return toReturn;
}

我不明白为什么 t 在高之后会有第二次递增。我也不知道如何从样本中得到高低。

【问题讨论】:

  • 您能否更具体地说明您要编写的音频文件类型?如果您询问如何将一堆整数写入二进制文件,您可能需要查看 ByteBufferIntBuffer 类,更一般的是 java.nio
  • 不知道有什么不清楚的地方,请告诉我。

标签: java file scala audio bytearray


【解决方案1】:

您发布的代码将一个示例流逐字节读取到示例数组中。代码假定,在流中,每两个 8 位字节形成一个 16 位样本,并且每个 NumOfChannels 通道都有一个样本。

因此,给定一组样本,如该代码返回的样本,

   int[][] samples; 

还有一个用于流式传输的字节数组,

   byte[] stream;

您可以通过这种方式构建反向字节流

  for (int i=0; i<NumOfSamples; i++) {
    for (int j=0; j<NumOfChannels; j++) {
      int sample=samples[i][j];
      byte low = (byte) (sample & 0xff) ;
              byte high = (byte) ((sample & 0xff00 ) >> 8);
              stream[((i*NumOfChannels)+j)*2] = low;    
              stream[(((i*NumOfChannels)+j)*2)+1] = high;         
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-08
    • 1970-01-01
    • 2011-07-02
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    相关资源
    最近更新 更多