Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create an ArrayList of bytes

I want to read bytes from a wave file into an array. Since the number of bytes read depends upon the size of the wave file, I'm creating a byte array with a maximum size of 1000000. But this is resulting in empty values at the end of the array. So, I wanted to create a dynamically increasing array and I found that ArrayList is the solution. But the read() function of the AudioInputStream class reads bytes only into a byte array! How do I pass the values into an ArrayList instead?

like image 563
Uday Kanth Avatar asked Jun 14 '11 08:06

Uday Kanth


2 Answers

ArrayList isn't the solution, ByteArrayOutputStream is the solution. Create a ByteArrayOutputStream write your bytes to it, and then invoke toByteArray() to get the bytes.

Example of what your code should look like:

in = new BufferedInputStream(inputStream, 1024*32);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] dataBuffer = new byte[1024 * 16];
int size = 0;
while ((size = in.read(dataBuffer)) != -1) {
    out.write(dataBuffer, 0, size);
}
byte[] bytes = out.toByteArray();
like image 80
Kaj Avatar answered Oct 30 '22 06:10

Kaj


You can have an array of byte like:

List<Byte> arrays = new ArrayList<Byte>();

To convert it back to arrays

Byte[] soundBytes = arrays.toArray(new Byte[arrays.size()]);

(Then, you will have to write a converter to transform Byte[] to byte[]).

EDIT: You are using List<Byte> wrong, I'll just show you how to read AudioInputStream simply with ByteArrayOutputStream.

AudioInputStream ais = ....;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int read;

while((read = ais.read()) != -1) {
    baos.write(read);
}

byte[] soundBytes = baos.toByteArray();

PS An IOException is thrown if frameSize is not equal to 1. Hence use a byte buffer to read data, like so:

AudioInputStream ais = ....;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;

while((bytesRead = ais.read(buffer)) != -1) {
    baos.write(buffer, 0, bytesRead);
}

byte[] soundBytes = baos.toByteArray();
like image 31
Buhake Sindi Avatar answered Oct 30 '22 06:10

Buhake Sindi