sammex
sammex

Reputation: 93

Playing sound through SourceDataLine.write - How to use the byte[]-Buffer with double values

I am a bit confused about how to use the byte[]-buffer from Java's SourceDataLine.write()-method: In my program, I try to generate audio data which I am playing back through a SourceDataLine. However, I am generating double-values and I use 4 bytes for one sample (my AudioFormat: new AudioFormat(8000f, 32, 1, true, true)).

What is the best way to convert one double into four bytes (/ to "play" a double)?

[PS: Is a sample size of 32 bis good for normal audio playback?]

Upvotes: 1

Views: 1112

Answers (1)

jaket
jaket

Reputation: 9341

The linked answer goes into great detail about this but I'll answer your direct question. First, I'm assuming that your double values are in the range of -1.0 to 1.0. That is typically the setup. To go to 32-bit signed integers you need to scale such that 1.0 becomes 0x7fffffff and -1.0 becomes 0x80000001 which can be done by simple multiplication.

int sampleInt = sampleDouble * 0x7fffffff;

Next you need to split the ints into bytes:

byte[0] = (byte)((sampleInt >> 24) & 0xff);
byte[1] = (byte)((sampleInt >> 16) & 0xff);
byte[2] = (byte)((sampleInt >> 8)  & 0xff);
byte[3] = (byte)((sampleInt >> 0)  & 0xff);

Depending on the endianess of your output you might need to swap the order.

Upvotes: 2

Related Questions