-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathGuitarString.java
executable file
·47 lines (40 loc) · 1.48 KB
/
GuitarString.java
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
package synthesizer;
//Make sure this class is public
public class GuitarString {
/** Constants. Do not change. In case you're curious, the keyword final means
* the values cannot be changed at runtime. We'll discuss this and other topics
* in lecture on Friday. */
private static final int SR = 44100; // Sampling Rate
private static final double DECAY = .996; // energy decay factor
/* Buffer for storing sound data. */
private BoundedQueue<Double> buffer;
/* Create a guitar string of the given frequency. */
public GuitarString(double frequency) {
int capacity = (int) Math.round(SR / frequency);
buffer = new ArrayRingBuffer<>(capacity);
for (int i = 0; i < capacity; i++) {
buffer.enqueue(0.0);
}
}
/* Pluck the guitar string by replacing the buffer with white noise. */
public void pluck() {
while (!buffer.isEmpty()) {
buffer.dequeue();
}
while (!buffer.isFull()) {
buffer.enqueue(Math.random() - 0.5);
}
}
/* Advance the simulation one time step by performing one iteration of
* the Karplus-Strong algorithm.
*/
public void tic() {
double dequeueSample = buffer.dequeue();
double peekSample = buffer.peek();
buffer.enqueue((dequeueSample + peekSample) / 2.0 * DECAY);
}
/* Return the double at the front of the buffer. */
public double sample() {
return buffer.peek();
}
}