import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JFrame; import jm.music.data.Note; import jm.music.data.Phrase; import jm.util.View; /** A utility for recording MIDI music using the keyboard. Users hit keys a-g to generate a note of duration proportional to the amount of time the key is held down. Simultaneously holding Shift creates a sharp, while Alt creates a flat. To go up an octave, hold the first mouse button down. This code was written hastily during a workshop. Be forewarned. */ public class Keyboard extends JFrame implements KeyListener { private char currNote; private double start; private double duration; private Phrase phrase; private int delta; private int offset; private int[] frequencies = { 57, 59, 60, 62, 64, 65, 67, 69, 71, 72, 74, 76, 77, 79 }; public static void main(String[] args) { Keyboard frame = new Keyboard(); } public Keyboard() { addKeyListener(this); requestFocusInWindow(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 400); setVisible(true); phrase = new Phrase(); } @Override public void keyPressed(KeyEvent e) { currNote = e.getKeyChar(); start = System.currentTimeMillis(); if ((e.getModifiers() & KeyEvent.SHIFT_MASK) > 0) { delta = 1; } else if ((e.getModifiers() & KeyEvent.ALT_MASK) > 0) { delta = -1; } else { delta = 0; } if ((e.getModifiersEx() & KeyEvent.BUTTON1_DOWN_MASK) > 0) { offset = 7; } else { offset = 0; } currNote = Character.toLowerCase(currNote); if (currNote == 'q') { View.notate(phrase); } } @Override public void keyReleased(KeyEvent e) { if (currNote >= 'a' && currNote <= 'g') { duration = System.currentTimeMillis() - start; int frequency = frequencies[offset + (currNote - 'a')]; phrase.addNote(new Note(frequency + delta, duration / 500.0)); } } @Override public void keyTyped(KeyEvent arg0) { } }