3

I'm reading data from .wav files through InputStream, and read() returns bytes. A sound processing library I use, only accepts float[] to process. After it it done it gives me a float[] back. Now I need to write to the Android's AudioTrack in byte format again.

How do I convert these bytes to floats[], and back to byte[]? I've searched a bit, but everything seemed to be kinda a different situation to mine, and all problems seemed to be solved in different ways... so i'm kinda lost right now.

If something like this conversion is already offered in some kind of library, i'd be glad to hear about that too!

Thanks!

user717572
  • 3,626
  • 7
  • 35
  • 60
  • What's the range of those floats? is it -1.0 to 1.0? Find that out and you can do the conversion easily. – Kayaman Oct 19 '13 at 12:54
  • 2
    http://stackoverflow.com/questions/9346746/convert-float-to-byte-to-float-again has the answer – arynaq Oct 19 '13 at 12:56

2 Answers2

1

You can use of java.nio.ByteBuffer. It has a lot of useful methods for pulling different types out of a byte array and should also handle most of your issues.

        byte[] data = new byte[36];
        ByteBuffer buffer = ByteBuffer.wrap(data);          
        float second = buffer.getFloat(); //This helps to 
        float x = 0;
        buffer.putFloat(x);
Deepak Bhatia
  • 6,230
  • 2
  • 24
  • 58
  • I tried this, `byte[] bytes = {32,-32,60,120}; ByteBuffer bbuf = ByteBuffer.wrap(bytes); while(bbuf.remaining()>0){ System.out.println(bbuf.getFloat());` But it just returns this: 3.798709E-19... Did I do something wrong? – user717572 Oct 19 '13 at 13:21
0

You just need to copy the bits. Try using BlockCopy.

 float[] fArray = new float[] { 1.0f, ..... };
 byte[] bArray= new byte[fArray.Length*4];
 Buffer.BlockCopy(fArray,0,bArray,0,bArray.Length);

The *4 is since each float is 4 bytes.

Lior Ohana
  • 3,467
  • 4
  • 34
  • 49