开发者

Converting array with samples into byte array

I have two-dimensional array of integers. First index indicates the number of channels. The second one indicates the number of sample in the channel. How can I save this array into the audio file? I know, I have to convert it to byte array, but I have no idea how to do that.

// edit

More info. I already have a class for drawing a waveform. It is here:

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

now I want to cut part of this wave and save it to the new file. So I have to cut part of int[][] samplesContainer, convert it to byte array (I don't know how) and then save it to file with the same format as audioInputStream.

// edit

OK. So the biggest problem is to write inverted function to this one:

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

I don't understand why there is secon开发者_开发技巧d incrementation of t, after high. I also have no idea how can i get high and low from sample.


The code you posted reads a sample stream, byte by byte, into the samples array. The code assumes that, in the stream, every two 8-bit bytes form a 16-bit sample, and that there is one sample for each of the NumOfChannels channels.

So, given an array of samples like the one returned by that code,

   int[][] samples; 

and a byte array for streaming,

   byte[] stream;

you might build the converse stream of bytes this way

  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;         
    }
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜