创建一个字节数组列表 [英] create an ArrayList of bytes
问题描述
我想将波形文件中的字节读入数组.由于读取的字节数取决于波形文件的大小,我正在创建一个最大大小为 1000000 的字节数组.但这会导致数组末尾出现空值.所以,我想创建一个动态增加的数组,我发现 ArrayList 是解决方案.但是 AudioInputStream 类的 read() 函数只将字节读取到字节数组中!如何将值传递到 ArrayList 中?
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?
推荐答案
你可以有一个字节数组,如:
You can have an array of byte like:
List<Byte> arrays = new ArrayList<Byte>();
将其转换回数组
Byte[] soundBytes = arrays.toArray(new Byte[arrays.size()]);
(然后,您必须编写一个转换器将Byte[]
转换为byte[]
).
(Then, you will have to write a converter to transform Byte[]
to byte[]
).
您使用的是List
错误,我将向您展示如何简单地使用读取
.AudioInputStream
ByteArrayOutputStream
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 如果 frameSize
不等于 1
,则抛出 IOException
.因此使用字节缓冲区来读取数据,如下所示:
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();
这篇关于创建一个字节数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!