aboutsummaryrefslogtreecommitdiff
path: root/PunchingBag/src/uk/ac/open/punchingbag/examples/SimpleKeyboard.java
blob: 1e791ee00f040a45901fe37c688a128723115316 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package uk.ac.open.punchingbag.examples;

import java.awt.Color;
import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;

import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MetaEventListener;
import javax.sound.midi.MetaMessage;
import javax.sound.midi.MidiEvent;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Synthesizer;
import javax.sound.midi.Track;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

import uk.ac.open.punchingbag.ButtonListener;
import uk.ac.open.punchingbag.Contact;
import uk.ac.open.punchingbag.PunchingBag;

public class SimpleKeyboard implements ButtonListener, Runnable {
	String soundDir = System.getProperty("user.dir")
			+ System.getProperty("file.separator");

	File[] keys = { new File(soundDir + "G4.wav"),
			new File(soundDir + "C5.wav"), new File(soundDir + "D5.wav"),
			new File(soundDir + "E5.wav"), new File(soundDir + "F5.wav"),
			new File(soundDir + "G5.wav") };

	static PunchingBag bag = PunchingBag.getBag();
	long lastActionTime = System.currentTimeMillis();
	boolean noising = false;

	public static final int DAMPER_PEDAL = 64;

	public static final int DAMPER_ON = 127;

	public static final int DAMPER_OFF = 0;

	public static final int END_OF_TRACK = 47;

	static final int[] offsets = { // add these amounts to the base value
	// A B C D E F G
			-4, -2, 0, 1, 3, 5, 7 };

	public static void main(String[] args) throws InvalidMidiDataException,
			MidiUnavailableException, IOException {

		try {
			bag.connectToArduinos();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		new SimpleKeyboard();

	}

	public SimpleKeyboard() {
		bag.addButtonListener(this);

		new Thread(this).start();
	}

	public void buttonPressed(int x, int y) {
		if (noising = true) {
			bag.clearLEDs();
			noising = false;
		}
		lastActionTime = System.currentTimeMillis();
		System.out.println("Button Pressed: " + x + " " + y);
		try {
			if (y < 3) {
				bag.fillRect(0, 0, 9, 4, Color.red, 500);
				playKey(5);
			} else if (y < 6) {
				bag.fillRect(0, 3, 9, 4, Color.red, 500);
				playKey(4);
			} else if (y < 9) {
				bag.fillRect(0, 6, 9, 4, Color.red, 500);

				playKey(3);

			} else if (y < 12) {
				bag.fillRect(0, 9, 9, 4, Color.red, 500);
				playKey(2);
			} else if (y < 15) {
				bag.fillRect(0, 12, 9, 4, Color.red, 500);
				playKey(1);
			} else {
				bag.fillRect(0, 15, 9, 4, Color.red, 500);
				playKey(0);
			}
		} catch (InvalidMidiDataException | MidiUnavailableException
				| IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	void playKey(int key) throws InvalidMidiDataException,
			MidiUnavailableException, IOException {

		try {
			AudioInputStream sound = AudioSystem.getAudioInputStream(keys[key]);
			DataLine.Info dataLine = new DataLine.Info(Clip.class,
					sound.getFormat());
			Clip clip = (Clip) AudioSystem.getLine(dataLine);
			clip.open(sound);
			clip.start();
		} catch (LineUnavailableException e) { // TODO Auto-generated catch
												// block
			e.printStackTrace();
		} catch (IOException e) { // TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedAudioFileException e) { // TODO Auto-generated catch
													// block
			e.printStackTrace();
		}

		/*char[] notes = { 'C', 'C' };

		String filename = null;
		int instrument = 0;
		int tempo = 120;

		// 16 ticks per quarter note.
		Sequence sequence = new Sequence(Sequence.PPQ, 16);

		// Add the specified notes to the track
		addTrack(sequence, instrument, tempo, notes);

		// Set up the Sequencer and Synthesizer objects
		Sequencer sequencer = MidiSystem.getSequencer();
		sequencer.open();
		Synthesizer synthesizer = MidiSystem.getSynthesizer();
		synthesizer.open();
		sequencer.getTransmitter().setReceiver(synthesizer.getReceiver());

		// Specify the sequence to play, and the tempo to play it at
		sequencer.setSequence(sequence);
		sequencer.setTempoInBPM(tempo);

		// And start playing now.
		sequencer.start();*/

	}

	@Override
	public void contact(Contact c) {
		// TODO Auto-generated method stub

	}

	/*
	 * This method parses the specified char[] of notes into a Track. The
	 * musical notation is the following: A-G: A named note; Add b for flat and
	 * # for sharp. +: Move up one octave. Persists. -: Move down one octave.
	 * Persists. /1: Notes are whole notes. Persists 'till changed /2: Half
	 * notes /4: Quarter notes /n: N can also be, 8, 16, 32, 64. s: Toggle
	 * sustain pedal on or off (initially off) >: Louder. Persists <: Softer.
	 * Persists .: Rest. Length depends on current length setting Space: Play
	 * the previous note or notes; notes not separated by spaces are played at
	 * the same time
	 */
	public static void addTrack(Sequence s, int instrument, int tempo,
			char[] notes) throws InvalidMidiDataException {
		Track track = s.createTrack(); // Begin with a new track

		// Set the instrument on channel 0
		ShortMessage sm = new ShortMessage();
		sm.setMessage(ShortMessage.PROGRAM_CHANGE, 0, instrument, 0);
		track.add(new MidiEvent(sm, 0));

		int n = 0; // current character in notes[] array
		int t = 0; // time in ticks for the composition

		// These values persist and apply to all notes 'till changed
		int notelength = 16; // default to quarter notes
		int velocity = 64; // default to middle volume
		int basekey = 60; // 60 is middle C. Adjusted up and down by octave
		boolean sustain = false; // is the sustain pedal depressed?
		int numnotes = 0; // How many notes in current chord?

		while (n < notes.length) {
			char c = notes[n++];

			if (c == '+')
				basekey += 12; // increase octave
			else if (c == '-')
				basekey -= 12; // decrease octave
			else if (c == '>')
				velocity += 16; // increase volume;
			else if (c == '<')
				velocity -= 16; // decrease volume;
			else if (c == '/') {
				char d = notes[n++];
				if (d == '2')
					notelength = 32; // half note
				else if (d == '4')
					notelength = 16; // quarter note
				else if (d == '8')
					notelength = 8; // eighth note
				else if (d == '3' && notes[n++] == '2')
					notelength = 2;
				else if (d == '6' && notes[n++] == '4')
					notelength = 1;
				else if (d == '1') {
					if (n < notes.length && notes[n] == '6')
						notelength = 4; // 1/16th note
					else
						notelength = 64; // whole note
				}
			} else if (c == 's') {
				sustain = !sustain;
				// Change the sustain setting for channel 0
				ShortMessage m = new ShortMessage();
				m.setMessage(ShortMessage.CONTROL_CHANGE, 0, DAMPER_PEDAL,
						sustain ? DAMPER_ON : DAMPER_OFF);
				track.add(new MidiEvent(m, t));
			} else if (c >= 'A' && c <= 'G') {
				int key = basekey + offsets[c - 'A'];
				if (n < notes.length) {
					if (notes[n] == 'b') { // flat
						key--;
						n++;
					} else if (notes[n] == '#') { // sharp
						key++;
						n++;
					}
				}

				addNote(track, t, notelength, key, velocity);
				numnotes++;
			} else if (c == ' ') {
				// Spaces separate groups of notes played at the same time.
				// But we ignore them unless they follow a note or notes.
				if (numnotes > 0) {
					t += notelength;
					numnotes = 0;
				}
			} else if (c == '.') {
				// Rests are like spaces in that they force any previous
				// note to be output (since they are never part of chords)
				if (numnotes > 0) {
					t += notelength;
					numnotes = 0;
				}
				// Now add additional rest time
				t += notelength;
			}
		}
	}

	// A convenience method to add a note to the track on channel 0
	public static void addNote(Track track, int startTick, int tickLength,
			int key, int velocity) throws InvalidMidiDataException {
		ShortMessage on = new ShortMessage();
		on.setMessage(ShortMessage.NOTE_ON, 0, key, velocity);
		ShortMessage off = new ShortMessage();
		off.setMessage(ShortMessage.NOTE_OFF, 0, key, velocity);
		track.add(new MidiEvent(on, startTick));
		track.add(new MidiEvent(off, startTick + tickLength));
	}

	@Override
	public void run() {
		while (true) {
			System.out.println("Checking last action time");
			if ((System.currentTimeMillis() - lastActionTime) > 20000) {
				System.out.println("Activating Noise");
				bag.noise(new Rectangle(0, 0, 9, 20));

				noising = true;

			} else {
				System.out.println("Waiting more");
			}
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();

			}
		}

	}

}