Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing a waveform (float array) as sound

Tags:

java

audio

I have a waveform that is represented as an array of floats from -1 to 1. Would it be possible to play this waveform as a repeated sound?

I've found numerous examples of playing audio from an array, but all relate to byte arrays, and require some very convoluted code.

like image 564
connerbryan Avatar asked Jun 30 '11 07:06

connerbryan


2 Answers

Without knowing much about it, why don't you just assign a range to the values, and play this range tone by tone.

-1   ...      1
50Hz ... 20,000Hz

You could easily calculate it like this:

//input is the float array
int minPitch = 50;
int maxPitch = 20000;

int pitch = (int)((input[idx] + 1) * ((maxPitch - minPitch) / 2) + minPitch);

This would give you the pitch of the value in the array.

like image 56
Bobby Avatar answered Sep 30 '22 10:09

Bobby


Assuming that your float array holds PCM data, and you want to play it in 8-bit, converting it to a byte array is easy:

              int off=(signed!=0 ? 0 : 128);
              for(int i=0; i<samples; i++){
                  val=(int)(pcm[i]*128. + 0.5);
                  if(val>127)
                    val=127;
                  else if(val<-128)
                    val=-128;
                  buffer[index++]=(byte)(val+off);
                }
              }

This code is slightly modifed code from JOrbis, here pcm is your array of floats, and buffer is the byte array.

like image 26
Denis Tulskiy Avatar answered Sep 30 '22 10:09

Denis Tulskiy