Galinho Salonica Galinho Salonica - 1 month ago 16
Java Question

JSyn function to play sounds

I'm recently working on a project on Java and I use SE 8. I have built a piano, which is playing music by playing several wav files, f.e. I have 5 organs and each button of my piano is one note of the selected music instrument. The instruments are selected from buttons on top.

However, I know I can also generate the music by using JSyn and not by just "calling" wavs to be played. Could anyone help on how to start, because I haven't found any tutorials to do that. I just need to find a way to use a function for my keys and just enter different values (I assume) to change the sound of every key. Any ideas?

Answer

If you want to play synthesized sounds using JSyn then you can find an example here that uses a MIDI keyboard:

https://github.com/philburk/jsyn/blob/master/tests/com/jsyn/examples/UseMidiKeyboard.java

It shows how to use a VoiceAllocator to manage the multiple voices. The key piece of code is:

double frequency = convertPitchToFrequency(noteNumber);
double amplitude = velocity / (4 * 128.0);
TimeStamp timeStamp = synth.createTimeStamp();
allocator.noteOn(noteNumber, frequency, amplitude, timeStamp);

If you want to play samples from WAV files then an example can be found here:

https://github.com/philburk/jsyn/blob/master/tests/com/jsyn/examples/PlaySample.java

On line 83 it says:

samplePlayer.rate.set(sample.getFrameRate());

That will play the sample at the original pitch that it was recorded at.

You can scale the rate so that it will play different pitches. For example, scale by 2.0 to play up an octave, or by 1.5 to play up a fifth:

samplePlayer.rate.set(1.5 * sample.getFrameRate());

If you scale too far up or down then it will sound odd. So you will probably want to use multiple samples and choose the sample that is closest to the desired pitch.