Debian Codegraph @

examples/book/digital-artists/chapter9/Listing9.3.ck

raw
1 // Listing 9.3 Add these overloaded pitch() functions to Simple
2
3 // Improved example of a resonant pop sound-making class
4 public class Simple {
5 // our Simple instrument patch
6 Impulse imp => ResonZ filt => dac;
7
8 // some default settings
9 100.0 => filt.Q => filt.gain;
10 1000.0 => filt.freq;
11
12 // set freq as we would any instrument
13 fun void freq(float freq)
14 {
15 freq => filt.freq;
16 }
17
18 // method to allow setting Q
19 fun void setQ(float Q)
20 {
21 Q => filt.Q;
22 }
23
24 // method to allow setting gain
25 fun void setGain(float gain)
26 {
27 filt.Q() * gain => imp.gain;
28 }
29
30 // play a note by firing impulse
31 fun void noteOn(float volume)
32 {
33 volume => imp.next;
34 }
35
36 // three ways of setting pitch
37 // one by float frequency
38 fun float pitch(float freq) // (1) Sets pitch as a float frequency in Hertz.
39 {
40 return freq => filt.freq;
41 }
42
43 // another to set pitch by MIDI note number
44 fun float pitch(int noteNum) // (2) Sets pitch using an integer MIDI note number.
45 {
46 return Std.mtof(noteNum) => filt.freq;
47 }
48
49 // another way to set pitch by noteName, capital A-G required
50 // Needs specific format: C4, D#5, Eb3, As3, Bf6
51 fun float pitch(string noteName) // (3) Sets pitch using a note name (string).
52 {
53 [21,23,12,14,16,17,19] @=> int notes[]; // Note numbers A thru G
54 noteName.charAt(0) - 65 => int base; // (4 Manipulates ASCII code to come up with array pointer.
55 notes[base] => int note;
56 0.0 => float freq;
57 if (base > -1 && base < 7) {
58 if (noteName.charAt(1) == '#') // either '#' symbol
59 notes[base] + 1 => note;
60 if (noteName.charAt(1) == 's') // or 's' counts for sharp
61 notes[base] + 1 => note;
62 if (noteName.charAt(1) == 'b') // either 'b' or
63 notes[base] - 1 => note;
64 if (noteName.charAt(1) == 'f') // 'f' counts for flat
65 notes[base] - 1 => note;
66 }
67 else {
68 <<< "Illegal Note Name!!" >>>;
69 return 0.0;
70 }
71 noteName.charAt(noteName.length()-1) - 48 => int oct;
72 if (oct > -1 && oct < 10) {
73 note + 12*oct => note; // (5) After figuring out note number,
74 return this.pitch(note); // calls MIDI pitch function.
75
76 }
77 else {
78 <<< "Illegal Octave!!" >>>;
79 return 0.0;
80 }
81 }
82 }
83
84 // Make a Simple, and test new pitch functions
85 Simple s;
86
87 // MIDI note number pitch
88 s.pitch(60); // (6) Tests MIDI integer pitch setting function.
89 1 => s.noteOn;
90 second => now;
91
92 // pitch as float frequency
93 s.pitch(440.0); // (7) Tests float pitch-setting function.
94 1 => s.noteOn;
95 second => now;
96
97 // pitch as note name string
98 s.pitch("G#5"); // (8) Tests string note name setting function.
99 1 => s.noteOn;
100 second => now;