How to read soundcard input stream at size of 2 bytes per sample? (Java)

89 Views Asked by At

I have this code:

final static AudioFormat format = new AudioFormat(48000, 16, 1, true, true);
TargetDataLine line;
    DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
    line=(TargetDataLine) AudioSystem.getLine(info);
    line.open(format);

    line.start();
    ByteArrayOutputStream out  = new ByteArrayOutputStream();
    int numBytesRead;
    byte[] data = new byte[16040];
    numBytesRead =  line.read(data, 0, data.length);

I want to to read 16-bit samples data but the function line.read() only allows me to use 8-bit data by variable byte - when I want to change it to int or short, it gives me an error. What can I do to get 16-bits data?

1

There are 1 best solutions below

0
On

You can convert your bytes using ByteBuffer class:

short[] shortArray = new shorts[data.lentgh / 2]; 
ByteBuffer            
   .wrap(data)
   .order(ByteOrder.LITTLE_ENDIAN)
   .asShortBuffer()
   .get(shortArray);

And yet another solution is to use DataInputStream which has a method .readShort() so you can read 16-bit data directly from your stream.