2

I'm trying to read a WAV file (and in the future also MP3 and Ogg) file as an array of floats in Java, much like libsndfile in C.

I'm looking at the various documentation in the javax.sampled packages, but I can't find a clear explanation on how to do that; I'd like to avoid recurring to external libraries if possible.

Any suggestion?

ergosys
  • 47,835
  • 5
  • 49
  • 70
Nicola Montecchio
  • 477
  • 1
  • 7
  • 18

2 Answers2

2

JavaSound will only give you "raw" access to the sound data embedded in the WAV file, e.g. 8 bit unsigned PCM or 16 bit signed PCM data (if your WAV files are PCM encoded). In either case, the value of each sample is in the range 0 to 255 or -32768 to 32767 and you simply have to shift the range to fit in -1f to 1f.

You should start with AudioSystem.getAudioInputStream(...) using an appropriate source (File, InputStream or URL), examine the format to check the sample size and the number of channels and then you can read and convert the PCM encoded data from the AudioInputStream accordingly.

jarnbjo
  • 33,923
  • 7
  • 70
  • 94
  • thanks, that is a good starting point. However, how do I scale them? I used the ByteBuffer class to read the integer values, however scaling does not work as expected: the negative values are scaled incorrectly, probably because of integer arithmetic stuff ... For example, normalizing on the first value, octave gives me 1.00000 1.06250 -0.12500 2.31250 0.75000 0.37500 -0.37500 0.50000 0.00000 0.87500 while java gives me 1.0 1.0625 -0.062744140625 2.3125 0.75 0.375 -0.312744140625 0.5 0.0 0.875 – Nicola Montecchio Aug 30 '10 at 13:13
0

found this page:

http://www.jsresources.org/faq_audio.html

see in particular 9.4: How can I reconstruct sample values from a byte array?

It works as expected, by comparing java's output with c++ (libsndfile) and matlab (wavread). I'm going to put the code on m github account when I have time

Nicola Montecchio
  • 477
  • 1
  • 7
  • 18