将带有样本的数组转换为字节数组

时间:2011-09-11 17:44:33

标签: java file scala audio bytearray

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

//编辑

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

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的第二次增量。我也不知道如何从样本中获得高低。

1 个答案:

答案 0 :(得分:1)

您发布的代码将一个逐字节的样本流读入samples数组。该代码假设在流中,每两个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;         
    }
  }
相关问题