create an ArrayList of bytes

前端 未结 3 1098
灰色年华
灰色年华 2021-01-05 06:01

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

3条回答
  •  轮回少年
    2021-01-05 06:50

    You can have an array of byte like:

    List arrays = new ArrayList();
    

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

提交回复
热议问题