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
|
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.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();
public static void main(String[] args) {
new SimpleKeyboard();
}
public SimpleKeyboard() {
bag.addButtonListener(this);
try {
bag.connectToArduinos();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Thread (this).start();
}
public void buttonPressed(int x, int y) {
lastActionTime = System.currentTimeMillis();
System.out.println("Button Pressed: " + x + " " + y);
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);
}
}
void playKey(int key) {
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();
}
}
@Override
public void contact(Contact c) {
// TODO Auto-generated method stub
}
@Override
public void run() {
while (true) {
if ((System.currentTimeMillis() - lastActionTime) > 4000) {
bag.noise(new Rectangle(0, 0, 9, 20));
}
}
}
}
|