2

I'm trying to find a way to use jack-audio in java. I've managed to create wrapper based on jnajack to get audio from jacks' port to java app (the original jnajack is not working with jack 1.9.8), but I can't find a way to manipulate data. I'm gettin' a List<FloatBuffer>, and for further data manipulation I need to convert it to byte[].

To put put it simple... firstly I want to save data to a file, but java sound api as I understand can only save data from TargetDataLine and/or byte[]. How can I convert FloatBuffer to byte[]? The only way I can find is floatbuffer.get(float[]) and somehow (don't know how) convert float[] to byte[].

kapex
  • 28,903
  • 6
  • 107
  • 121
K-O
  • 79
  • 2
  • 3

2 Answers2

7

How can I convert FloatBuffer to byte[]?

FloatBuffer floatbuffer;

ByteBuffer byteBuffer = ByteBuffer.allocate(floatbuffer.capacity() * 4);
byteBuffer.asFloatBuffer().put(floatbuffer);
byte[] bytearray = byteBuffer.array();

You may have to change the byte order.

Ishtar
  • 11,542
  • 1
  • 25
  • 31
1

So jnajack uses a different representation of the audio data than the standard java sound api functions.

I don't see it in jnajack's specs, but I imagine it represents the audio as floats between -1 and 1.

I'm not too familiar with the Java Sound API, but I could imagine it uses bytes ranged between -128 and 127.

In other words, you'd have to convert between the two by multiplying by 128.

I'd say the neat way to do this would be byte converted = Float.valueOf(original * 128).byteValue(). If needed it's probably possible to do this with only primitives, which should be faster.

Arnout Engelen
  • 6,709
  • 1
  • 25
  • 36
  • it's not jnajack uses a different representation of the audio data! jnajack(as jjack too) is simply a JNA/JNI for Jack Audio Tool. the problem. – K-O Sep 04 '11 at 13:53
  • `Float.valueOf(original * 128).byteValue()` is exactly the same as `(byte)(original * 128)`. However, the value `1.0` will wrap to `-128`. – Aleksandr Dubinsky Jan 22 '15 at 18:07