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 } catch (ArrayIndexOutOfBoundsException x) {
32 * Plays the appropriate MIDI NoteOff event.
34 public void keyReleased(KeyEvent e) {
36 // Retrieves the notenumber from the conversion array.
37 int noteNumber = keyToNote[e.getKeyCode()];
38 // Sends the NoteOff event.
39 Moosique.getActiveChannel().noteOff(noteNumber);
40 isOn[noteNumber] = false;
41 } catch (ArrayIndexOutOfBoundsException x) {
47 * Sets the octave of the lower part of the keyboard (default = 4)
48 * @param n the octave to start at
50 public void setOctave(int n) {
54 /** Maps keycodes (array indices) to MIDI note numbers using the following layout:
56 * 2 3 5 6 7 9 0 => # # # # # # #
57 * q w e r t y u i o p => c d e f g a b c d e
58 * s d g h j l => # # # # # #
59 * z x c v b n m , . => c d e f g a b c d
62 keyToNote[KeyEvent.VK_Q] = startNote;
63 keyToNote[83] = startNote + 1;
64 keyToNote[88] = startNote + 2;
65 keyToNote[68] = startNote + 3;
66 keyToNote[67] = startNote + 4;
67 keyToNote[86] = startNote + 5;
68 keyToNote[71] = startNote + 6;
69 keyToNote[66] = startNote + 7;
70 keyToNote[72] = startNote + 8;
71 keyToNote[78] = startNote + 9;
72 keyToNote[74] = startNote + 10;
73 keyToNote[77] = startNote + 11;
74 keyToNote[44] = startNote + 12;
75 keyToNote[76] = startNote + 13;
76 keyToNote[46] = startNote + 14;
77 keyToNote[81] = startNote + 12;
78 keyToNote[50] = startNote + 13;
79 keyToNote[87] = startNote + 14;
80 keyToNote[51] = startNote + 15;
81 keyToNote[69] = startNote + 16;
82 keyToNote[82] = startNote + 17;
83 keyToNote[53] = startNote + 18;
84 keyToNote[84] = startNote + 19;
85 keyToNote[54] = startNote + 20;
86 keyToNote[89] = startNote + 21;
87 keyToNote[55] = startNote + 22;
88 keyToNote[85] = startNote + 23;
89 keyToNote[73] = startNote + 24;
90 keyToNote[57] = startNote + 25;
91 keyToNote[79] = startNote + 26;
92 keyToNote[48] = startNote + 27;
93 keyToNote[80] = startNote + 28;