Search code examples
javaarraysaudiosamplingtrigonometry

Synthesizing sampled sound


I am trying to convert an array of integers into a sound representation. Currently, I'm playing each value as an individual short tone but I would like to create a single sampled wave from the information and play it back, like so:

image

Each red dot representing a data point. Ideally I'd like to end up with a simple method such as playSound(int[] array);. I've looked through the javax.sound.sampled package but I dont know where to start.


Solution

  • To start with, an array of samples is not enough information to play a sound.

    • You also need to specify the sample rate. (e.g. 50 samples repeating -1,+1,etc. could be a 50 hz sine wave if recorded at 25 samples/second or a 12.5 hz wave if recorded at 50 samples/second (my math may be off)).

    • Another thing that is needed is how the sound is stored. Is MAX_INT your highest sound or is 255 your peak volume?

    • You also need to specify an encoding. You probably want either PCM_SIGNED or PCM_UNSIGNED (depending on if you have negative samples) or there may be even another encoding you want to use.

    The javax.sound.sampled package represents this information in the AudioFormat class.

    You will need to construct an audio format that reflects the method in which your audio was samples. For example, if your samples took up the full integer range and you represented each sample with an integer and you sampled at 22,000 samples per second and it was a mono sound you would construct the following AudioFormat...

    AudioFormat desiredFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,22000,32,1,32,22000,true);
    

    Once you have an AudioFormat you can open a line and dump audio to it. This page demonstrates how to do that (they cheat and are playing an audio file so they get the AudioFormat from the file).

    Of course, you might not be able to open a line for all formats so you might have to do some conversion. All of this said, there may be Java sound libraries out there which can make this a lot easier.