创建一个字节数组

我想将波形文件中的字节读入数组。 由于读取的字节数取决于波形文件的大小,因此我创建了一个最大大小为1000000的字节数组。但这会导致数组末尾出现空值。 所以,我想创建一个动态增加的数组,我发现ArrayList是解决方案。 但是AudioInputStream类的read()函数只将字节读入字节数组! 如何将值传递给ArrayList?

你可以有一个像这样的字节数组:

List arrays = new ArrayList(); 

将其转换回数组

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

(然后,您必须编写转换器以将Byte[]转换为byte[] )。

编辑:您正在使用List错误,我将向您展示如何使用ByteArrayOutputStream简单地读取AudioInputStream

 AudioInputStream ais = ....; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int read; while((read = ais.read()) != -1) { baos.write(read); } byte[] soundBytes = baos.toByteArray(); 

PS如果frameSize不等于1则抛出IOException 。 因此使用字节缓冲区来读取数据,如下所示:

 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(); 

ArrayList不是解决方案, ByteArrayOutputStream是解决方案。 创建一个ByteArrayOutputStream将字节写入它,然后调用toByteArray()来获取字节。

代码应该是什么样子的示例:

 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(); 

这样的事应该做​​:

 List myBytes = new ArrayList(); //assuming your javax.sound.sampled.AudioInputStream is called ais while(true) { Byte b = ais.read(); if (b != -1) { //read() returns -1 when the end of the stream is reached myBytes.add(b); } else { break; } } 

对不起,如果代码有点不对劲。 我有一段时间没有做过Java。

另外,如果你将它实现为while(true)循环,请小心:)

编辑:这是另一种方法,每次读取更多字节:

 int arrayLength = 1024; List myBytes = new ArrayList(); while(true) { Byte[] aBytes = new Byte[arrayLength]; int length = ais.read(aBytes); //length is the number of bytes read if (length == -1) { //read() returns -1 when the end of the stream is reached break; //or return if you implement this as a method } else if (length == arrayLength) { //Array is full myBytes.addAll(aBytes); } else { //Array has been filled up to length for (int i = 0; i < length; i++) { myBytes.add(aBytes[i]); } } } 

请注意,两个read()方法都抛出一个IOException - 处理它仍然是读者的练习!