Can someone help me understand this loop?
byte tempBuffer[] = new byte[64*1024];
for (int i = 0; i < tempBuffer.length; i++) {
wavPanel.addAudioByte(tempBuffer[i]);
}
In my opinion it works like this:
- cycle as many times as the size of tempBuffer in the meantime
- fill开发者_StackOverflow社区 the tempBuffer with bytes or maybe execute the
addAudioByte()
method of thewavPanel
object n times
Sorry for my confusion.
Can someone tell me, in words, what the loop does?
Thanks in advance.
Carlos Frerera
The byte array has size 64*1024 so the loop is executed 64*1024 times. Every time the loop executes, the next byte from the byte array is passed to the method addAudioByte (starting with the 0th. element) as a parameter.
What the method addAudioByte(byte byt) does, is depending on the implementation of this method.
To answer your question you asked in the last answer:
byte b stands for the parameter which is passed to your method addAudioByte(...). This means to call this method you have to pass the datatype byte to this method. This link explains the byte data type.
It calls
wavPanel.addAudioByte(...)
for each of the 64*1024 (65536) bytes in the tempBuffer, like so:
wavPanel.addAuditByte(tempBuffer[0]);
wavPanel.addAuditByte(tempBuffer[1]);
wavPanel.addAuditByte(tempBuffer[2]);
wavPanel.addAuditByte(tempBuffer[3]);
wavPanel.addAuditByte(tempBuffer[4]);
....
eventually ending on the 64*1024-1 byte
...
wavPanel.addAuditByte(tempBuffer[65535]);
Remember, that while there are 65*1024 bytes in this array, since arrays start their indexing a 0, you can't ask for the 65536th index, because if you counted them starting at zero, it would tempBuffer[65536]
would actually be the 65537th byte
Here's a smaller example to show the basics. Lets take a smaller array with just four values:
byte[] tempBuffer = new byte[4];
tempBuffer[0] = 10;
tempBuffer[1] = 10;
tempBuffer[2] = 10;
tempBuffer[3] = 10;
tempBuffer.length
is the size of the array (4 slots), the index of the first value in the array is 0
, the index of the last one is (tempBuffer.length-1) = 3
.
Now the loop:
for (int i = 0; i < tempBuffer.length; i++) {
// do something
}
This will loop 4 times and i
will be incremented by 1 on each iteration. So in the first iteration, i is 0
, in the last one, i
has a value od 3
.
wavPanel.addAudioByte(tempBuffer[i]);
This is the last 'java magic'. tempBuffer[i] is the value of the ith 'slot' in the array, so if i
is 0
, tempBuffer[0]
is 10
(according to our initialization). And this value is passed to the method wavPanel.addAudioByte(byte b)
.
精彩评论