1 import javax.sound.midi.*;
2 import java.awt.event.*;
5 * A keyboard listener emulating a synthesizer.
7 * @author Einar Pehrson
10 public class MooKeyboard extends KeyAdapter {
12 private boolean[] isOn = new boolean[120];
13 private static int startNote = 48;
14 private static final int[] keyToNote = new int[120];
17 * Plays the appropriate MIDI NoteOn event.
19 public void keyPressed(KeyEvent e) {
21 // Retrieves the notenumber from the conversion array.
22 int noteNumber = keyToNote[e.getKeyCode()];
23 // If note is not already on and the key is mapped to a note, sends the NoteOn event.
24 if (!isOn[noteNumber] && noteNumber > 0) Moosique.getActiveChannel().noteOn(noteNumber, 127);
25 isOn[noteNumber] = true;
26 System.out.println("NoteON");
27 } catch (ArrayIndexOutOfBoundsException x) {
33 * Plays the appropriate MIDI NoteOff event.
35 public void keyReleased(KeyEvent e) {
37 // Retrieves the notenumber from the conversion array.
38 int noteNumber = keyToNote[e.getKeyCode()];
39 // Sends the NoteOff event.
40 Moosique.getActiveChannel().noteOff(noteNumber);
41 isOn[noteNumber] = false;
42 System.out.println("NoteOFF");
43 } catch (ArrayIndexOutOfBoundsException x) {
49 * Sets the octave of the lower part of the keyboard (default = 4)
50 * @param n the octave to start at
52 public static void setOctave(int n) {
56 /** Maps keycodes (array indices) to MIDI note numbers using the following layout:
58 * 2 3 5 6 7 9 0 => # # # # # # #
59 * q w e r t y u i o p => c d e f g a b c d e
60 * s d g h j l => # # # # # #
61 * z x c v b n m , . => c d e f g a b c d
64 keyToNote[KeyEvent.VK_Q] = startNote;
65 keyToNote[83] = startNote + 1;
66 keyToNote[88] = startNote + 2;
67 keyToNote[68] = startNote + 3;
68 keyToNote[67] = startNote + 4;
69 keyToNote[86] = startNote + 5;
70 keyToNote[71] = startNote + 6;
71 keyToNote[66] = startNote + 7;
72 keyToNote[72] = startNote + 8;
73 keyToNote[78] = startNote + 9;
74 keyToNote[74] = startNote + 10;
75 keyToNote[77] = startNote + 11;
76 keyToNote[44] = startNote + 12;
77 keyToNote[76] = startNote + 13;
78 keyToNote[46] = startNote + 14;
79 keyToNote[81] = startNote + 12;
80 keyToNote[50] = startNote + 13;
81 keyToNote[87] = startNote + 14;
82 keyToNote[51] = startNote + 15;
83 keyToNote[69] = startNote + 16;
84 keyToNote[82] = startNote + 17;
85 keyToNote[53] = startNote + 18;
86 keyToNote[84] = startNote + 19;
87 keyToNote[54] = startNote + 20;
88 keyToNote[89] = startNote + 21;
89 keyToNote[55] = startNote + 22;
90 keyToNote[85] = startNote + 23;
91 keyToNote[73] = startNote + 24;
92 keyToNote[57] = startNote + 25;
93 keyToNote[79] = startNote + 26;
94 keyToNote[48] = startNote + 27;
95 keyToNote[80] = startNote + 28;