K-O
K-O

Reputation: 79

convert from floatbuffer to byte[]

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[].

Upvotes: 2

Views: 4212

Answers (2)

Ishtar
Ishtar

Reputation: 11662

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.

Upvotes: 7

Arnout Engelen
Arnout Engelen

Reputation: 6907

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.

Upvotes: 1

Related Questions