| 1 |
// Listing 8.2 Parallel, multithreaded, concurrent drum machine |
| 2 |
|
| 3 |
// by Drummond Base, October 2020 |
| 4 |
// First define some global durations |
| 5 |
1 :: second => dur whole; // (1) Defines whole, half, and quarter note durations. |
| 6 |
whole / 2 => dur half; |
| 7 |
whole / 4 => dur quarter; |
| 8 |
|
| 9 |
// Kick drum function |
| 10 |
fun void kick() { // (2) Function to play kick drum. |
| 11 |
SndBuf kick => dac; |
| 12 |
me.dir()+"/audio/kick_01.wav" => kick.read; |
| 13 |
// only play every whole note |
| 14 |
while (true) { |
| 15 |
whole => now; |
| 16 |
0 => kick.pos; |
| 17 |
} |
| 18 |
} |
| 19 |
|
| 20 |
// Snare drum function |
| 21 |
fun void snare() { // (3) Function to play snare drum. |
| 22 |
SndBuf snare => dac; |
| 23 |
me.dir()+"/audio/snare_01.wav" => snare.read; |
| 24 |
// play with half note tempo |
| 25 |
while (true) { |
| 26 |
half => now; |
| 27 |
0 => snare.pos; |
| 28 |
} |
| 29 |
} |
| 30 |
|
| 31 |
// Hi hat drum function |
| 32 |
fun void hihat() { // (4) Function to play hi-hat. |
| 33 |
SndBuf hihat => dac; |
| 34 |
me.dir()+"/audio/hihat_01.wav" => hihat.read; |
| 35 |
0.2 => hihat.gain; |
| 36 |
// play every quarter note |
| 37 |
while (true) { |
| 38 |
quarter => now; |
| 39 |
0 => hihat.pos; |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
// Main program to spork our individual drum functions |
| 44 |
// start off with kick drum for two measures |
| 45 |
spork ~ kick(); // (5) Sporking kick function starts it playing |
| 46 |
2*whole => now; |
| 47 |
|
| 48 |
// then add in hi hat after two measures |
| 49 |
spork ~ hihat(); // (6) Sporks hi-hat after a time |
| 50 |
2*whole => now; |
| 51 |
|
| 52 |
// add snare, but on off beats (quarter delayed start) |
| 53 |
quarter => now; |
| 54 |
spork ~ snare(); // (7) Sporks snare starting on off beat |
| 55 |
|
| 56 |
// let it run for four more measures |
| 57 |
4*whole => now; // (8) Lets it all run for four more measures |