To convert anything to anything else, you need to convert to a common thing in the middle, and that usually is a number.
So, basically you want:
[ set of keys ] --> [ 0, 1, 2, 3, 4.... ] -> [ musical notes ]
So this reduces the problem to:
1) How do I convert keys into a number from 0...n ?
2) How do I convert a number from 0...n into a musical note?
Whenever you want to convert something to something else, think of it this way, and then the problem gets easier.
To convert a key into a number, you can use the key variable, which gives you a number which represents the ASCII value of the letter you are typing (more or less). We can look at those values and convert them to more useable numbers, so that they count up as you go across the top "qwerty" row of the keyboard, like so:
- void keyPressed() {
- int v = keyToNumber();
- println(v);
- }
- int keyToNumber()
- {
- if (key == 'q') return 0;
- else if (key == 'w') return 1;
- else if (key == 'e') return 2;
- else if (key == 'r') return 3;
- else if (key == 't') return 4;
- else if (key == 'y') return 5;
- // etc.
- return 0;
- }
Once you have the number, there are tons of ways to convert numbers to notes. You can convert them to a MIDI Note Number, in which case, you are basically already there. Just add an offset So, for example, if you wanted a scale that starts on Middle C, you would add 60. (Read up on MIDI if you don't know what it is).
int note = keyToNumber() + 60;
Or, you might want to produce a frequency in Hz (read up on Digital Audio to learn more about how frequency relates to pitch)
float freq = 440 * pow(2, keyToNumber()/12.0);
or you might want to trigger one of a set of samples.
int sampleNumber = keyToNumber();
String sampleName = "sample_" + sampleNumber + ".mp3";
Once you've got the key converted into a useful number, there are lots of ways to do it.