Reading wav file java vs matlab

I am trying to read the data of a WAV file in both java and matlab and save it as an array of bytes.

In java, the code is as follows:

public byte[] readWav2(File file) throws UnsupportedAudioFileException, IOException { AudioFormat audioFormat; AudioInputStream inputAIS = AudioSystem.getAudioInputStream(file); audioFormat = inputAIS.getFormat(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Read the audio data into a memory buffer. int nBufferSize = BUFFER_LENGTH * audioFormat.getFrameSize(); byte[] abBuffer = new byte[nBufferSize]; while (true) { int nBytesRead = inputAIS.read(abBuffer); if (nBytesRead == -1) { break; } baos.write(abBuffer, 0, nBytesRead); } byte[] abAudioData = baos.toByteArray(); return abAudioData; } 

In Matlab, I use the wavread function:

 [Y, FS] = wavread('sound.wav', 'native'); 

But the results that I get are different.

In java, the first 20 bytes:

 53, 0, 19, 0, -71, -1, -80, -1, -99, -1, 10, 0, 87, 0, -69, -1, 123, -1, -77, -1 

In Matlab:

 53, 19, -71, -80, -99, 10, 87, -69, -133, -77, 38, 143, 13, -100, 39, 45, -52, -83, -82, 56 

Why is every second byte in java equal to 0 or -1, where in Matlab is not? Although I skip 0 and -1, where in java is 123 for matlab -133? Why is it different?

+4
source share
1 answer

Java returns you 16-bit signed PCM data. Since each pattern has 16 bits and a byte contains 8 bits, each pattern spans two bytes in Java. What Matlab returns is an array of 16-bit samples directly.

In principle, the data is the same. It is just different in memory.

To access the samples in a simpler way from Java, you can do some bitwise arithmetic, for example:

 int firstSample = (abAudioData[0]&0xFF) | (abAudioData[1]<<8); 

Another way to read samples is with java.nio buffers:

 ByteBuffer bb = ByteBuffer.wrap(abAudioData); bb.order(ByteOrder.LITTLE_ENDIAN); ShortBuffer sb = bb.asShortBuffer(); int firstSample = sb.get(); 
+5
source

Source: https://habr.com/ru/post/1395436/


All Articles