Debian Codegraph @

examples/book/digital-artists/chapter9/SmartMandolin/MandoPlayer.ck

raw
1 // Listing 9.20 Smart mandolin instrument and player class
2 // Four Mando "strings", plus some smarts
3 // by Perry R. Cook, March 2013
4
5 public class MandoPlayer { // (1) Public MandoPlayer class definition.
6 // make an array of four mandolin strings and connect them up
7 Mandolin m[4]; // (2) Contains four Mandolin UGens.
8 m[0] => JCRev rev => dac; // (3) Hooks them all up so you can hear them.
9 m[1] => rev;
10 m[2] => rev;
11 m[3] => rev;
12 0.25 => rev.gain;
13 0.02 => rev.mix;
14
15 // set all four string frequencies in one function
16 fun void freqs(float gStr, float dStr, float aStr, float eStr)
17 { // (4) Sets all four string frequencies
18 m[0].freq(gStr);
19 m[1].freq(aStr);
20 m[2].freq(dStr);
21 m[3].freq(eStr);
22 }
23
24 // set all four string notes in one function
25 fun void notes(int gNote, int dNote, int aNote, int eNote) {
26 m[0].freq(Std.mtof(gNote)); // (5) Sets all four string note numbers...
27 m[1].freq(Std.mtof(dNote)); // (6) ...using .mtof.
28 m[2].freq(Std.mtof(aNote));
29 m[3].freq(Std.mtof(eNote));
30 }
31
32 // a few named chords to get you started, add your own!!
33 fun void chord(string which) { // (7) Chords by name.
34 if (which == "G") this.notes(55,62,71,79); // (8) G Chord is G3, D4, B4, G5.
35 else if (which == "C") this.notes(55,64,72,79);
36 else if (which == "D") this.notes(57,62,69,78);
37 else <<< "I don't know this chord: ", which >>>;
38 }
39
40 // roll a chord from lowest note to highest at rate
41 fun void roll(string chord, dur rate)
42 { // (9) Chord roll (arpeggiate) function.
43 this.chord(chord); // (10) Sets chord by string using MandoPlayer .chord function.
44 for (0 => int i; i < 4; i++) {
45 1 => m[i].noteOn; // (11) Plays notes one at a time...
46 rate => now; // (12) ...with rate duration between.
47 }
48 }
49
50 // Archetypical tremolo strumming
51 fun void strum(int note, dur howLong)
52 { // (13) Strumming function (tremolo).
53 int whichString;
54 if (note < 62) 0 => whichString; // (14) Figures out which string to strum.
55 else if (note < 69) 1 => whichString;
56 else if (note < 76) 2 => whichString;
57 else 3 => whichString;
58 Std.mtof(note) => m[whichString].freq; // (15) Sets frequency.
59 now + howLong => time stop; // (16) Time to stop strumming...
60 while (now < stop) { // (17) ...do it until you get to that time.
61 Std.rand2f(0.5,1.0) => m[whichString].noteOn; // (18) Somewhat random volume.
62 Std.rand2f(0.06,0.09) :: second => now; // (19) Somewhat random time.
63 }
64 }
65
66 // Damp all strings by amount
67 // 0.0 = lots of damping, 1.0 = none
68 fun void damp(float amount) { // (20) Damping function.
69 for (0 => int i; i < 4; i++) {
70 amount => m[i].stringDamping;
71 }
72 }
73
74 // END the MandoPlayer Class Definition
75 // (21) Whew! Finished defining the smart Mandolin player class.
76 }