Skip to content

Instantly share code, notes, and snippets.

@niusounds
Last active July 20, 2016 09:38
Show Gist options
  • Save niusounds/3518d637ae3aa0a049d3ea8373a41e8f to your computer and use it in GitHub Desktop.
Save niusounds/3518d637ae3aa0a049d3ea8373a41e8f to your computer and use it in GitHub Desktop.
細切れの配列データを少しずつ書き込み、バッファがいっぱいになったときに通知を受けるクラス。
public class BufferedData {
public interface OnBufferFilledListener {
void onBufferFilled(float[] buffer);
}
private final float[][] buffers;
private int currentBufferIndex;
private int indexInCurrentBuffer;
private OnBufferFilledListener listener;
public BufferedData(int bufferCount, int bufferSize) {
buffers = new float[bufferCount][];
for (int i = 0; i < buffers.length; i++) {
buffers[i] = new float[bufferSize];
}
}
public void setListener(OnBufferFilledListener listener) {
this.listener = listener;
}
public OnBufferFilledListener getListener() {
return listener;
}
public void write(float[] data, int offset, int size) {
float[] buf = buffers[currentBufferIndex];
if (buf.length - indexInCurrentBuffer >= size) {
System.arraycopy(data, offset, buf, indexInCurrentBuffer, size);
indexInCurrentBuffer += size;
if (indexInCurrentBuffer == buf.length) {
notifyToListener();
}
} else {
for (int i = 0; i < size; i++) {
buf[indexInCurrentBuffer++] = data[i];
if (indexInCurrentBuffer == buf.length) {
notifyToListener();
buf = buffers[currentBufferIndex];
}
}
}
}
private void notifyToListener() {
if (listener != null) {
listener.onBufferFilled(buffers[currentBufferIndex]);
}
currentBufferIndex = (currentBufferIndex + 1) % buffers.length;
indexInCurrentBuffer = 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment