1

I have a method that reads a 16 bit WAVE file, like this:

FileInputStream in = new FileInputStream(file);
byte[] bytes = new byte[8*Number];
do {
    readSize = in.read(bytes, 0, 8*Number);
    ...
} while (...);

I then need to convert each pair of bytes in bytes[] into a short. That is, I better be sure that readSize is even! I know that readSize is not necessarily equal to 8*Number, and that it can be smaller...

Is this parity of readSize somehow guaranteed by the read method, or I must check after the in.read line?

EDIT

Since I also need that readSize to be equal to 8*Number and not just even, I use this workaround, where I am reading once and again until I get all the data I need:

        FileInputStream in = new FileInputStream(f);
        int i, readSize, chunkPerBar = 8*Number;
        byte[] bytes = new byte[chunkPerBar];
        double mean;
        do {
            // If I cannot read *exactly* chunkPerBar bytes, keep adding or exit
            readSize = in.read(bytes, 0, chunkPerBar);
            while ((readSize < chunkPerBar) && (in.available() > 0))
                readSize += in.read(bytes, readSize, chunkPerBar - readSize);
            if (readSize < chunkPerBar) break;  // Discard the last chunk if < chunkPerBar

            mean = 0;
            for (i = 0; i < chunkPerBar / 2; i++) {
                aux = (short)( ( bytes[2*i] & 0xff )|( bytes[2*i+1] << 8 ) );
                mean += aux * aux;
            }

            waveform.drawNewBar(mean/chunkPerBar);
        } while (in.available() > 0);
        in.close();
        } catch {...}
Luis A. Florit
  • 2,169
  • 1
  • 33
  • 58
  • You need to check, in principle read can return any number less than or equal to the buffer size. – tgdavies May 27 '22 at 04:58
  • DataInputStream reads shorts in BigEndian, while WAVE are LittleEndian. No? – Luis A. Florit May 27 '22 at 15:02
  • What does it matter? Just swap the bytes – blackapps May 27 '22 at 19:37
  • In my case, I do not quite yet see the advantage. If I use `DataInputStream.readShort()` to read shorts one by one, then the routine is *very* slow (it is to display a waveform) - I just tried. So I need to use buffers anyway, and since I need to compute RMS of *constant* length chunks of audio data, I need to ensure that the correct constant length is being written. So the only savings I see would be to convert 2 byte to short, which is pretty inexpensive, and with `DataInputStream` I need to swap anyway. Hope this makes sense, or maybe I am missing something? I will add an EDIT for this. – Luis A. Florit May 27 '22 at 23:38

0 Answers0