«Keyboard phrase recorder and Pattern Array printer» by Frank Bonarrigo

on 10 Jul'24 08:12 in patternguisequencer

One of 2 Keyboards, The other will play a sample. This is one with a standard default Synth. Activating the Keyboard button allows you to play the keyboard with your computer Keyboard (Mac, not sure if Windows works). Number buttons change octaves. Start Time Capture records little phrases including Chords. Just copy paste your degree array and dur array into your Pattern setup . Do math in the array to make it work with your Key. It is setup for the Chromatic scale.

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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
(
// Function to create our keyboard
~createKeyboard = {
    var startTime, currentOctave = 0;
    var keyboardActive = false;  // Variable to track keyboard activation state
    var chordNotes = Set.new;  // Set to store currently active notes for chord detection

    // Define a simple synth with an envelope
    SynthDef(\keyboardSynth, { |out=0, freq=440, amp=0.5, gate=1|
        var sig, env;
        env = EnvGen.kr(Env.adsr(0.01, 0.1, 0.5, 0.1), gate, doneAction: 2);
        sig = SinOsc.ar(freq) * env * amp;
        Out.ar(out, sig ! 2);
    }).add;

    // Create a window for the keyboard
    ~win = Window("Two-Octave Chromatic Keyboard with Octave Shift and Chord Recording", Rect(100, 100, 1000, 400)).front;

    // Define note names and their corresponding chromatic scale degrees for two octaves
    ~notes = [\C, \Cs, \D, \Ds, \E, \F, \Fs, \G, \Gs, \A, \As, \B,
               \C, \Cs, \D, \Ds, \E, \F, \Fs, \G, \Gs, \A, \As, \B];
    ~scaleDegrees = (0..23);

    // Define keyboard mapping
    ~keyboardMap = Dictionary[
        $a -> 0, $w -> 1, $s -> 2, $e -> 3, $d -> 4, $f -> 5, $t -> 6, $g -> 7, $y -> 8, $h -> 9, $u -> 10, $j -> 11,
        $k -> 12, $o -> 13, $l -> 14, $p -> 15, $; -> 16, $' -> 17,
        $z -> 0, $x -> 2, $c -> 4, $v -> 5, $b -> 7, $n -> 9, $m -> 11, $, -> 12, $. -> 14, $/ -> 16
    ];

    // Array to store the sequence of played notes and chords with timing
    ~sequence = List[];

    // Timing capture flag
    ~capturingTime = false;

    // Dictionary to store active synths
    ~activeSynths = Dictionary.new;

    // Function to play a note
    ~playNote = { |degree|
        var adjustedDegree = degree + (currentOctave * 12);
        var freq = (adjustedDegree + 60).midicps;
        var synth;

        // Stop the previous synth for this degree if it exists
        ~activeSynths[adjustedDegree].do({ |syn| syn.set(\gate, 0) });

        synth = Synth(\keyboardSynth, [\freq, freq, \amp, 0.5]);
        ~activeSynths[adjustedDegree] = synth;

        chordNotes.add(adjustedDegree);

        if(~capturingTime, {
            var elapsedTime = Main.elapsedTime - startTime;
            if(chordNotes.size > 1, {
                ~sequence.add([chordNotes.asArray.sort, elapsedTime.round(0.001)]);
            }, {
                ~sequence.add([adjustedDegree, elapsedTime.round(0.001)]);
            });
        }, {
            if(chordNotes.size > 1, {
                ~sequence.add([chordNotes.asArray.sort, nil]);
            }, {
                ~sequence.add([adjustedDegree, nil]);
            });
        });

        // Update button state
        if(degree < 24, {
            ~buttons[degree].states = [[~notes[degree].asString, Color.white, Color.black]];
            AppClock.sched(0.2, {
                ~buttons[degree].states = [[~notes[degree].asString, Color.black, Color.white]];
                nil
            });
        });
    };

    // Function to stop a note
    ~stopNote = { |degree|
        var adjustedDegree = degree + (currentOctave * 12);
        ~activeSynths[adjustedDegree].do({ |syn| syn.set(\gate, 0) });
        ~activeSynths[adjustedDegree] = nil;
        chordNotes.remove(adjustedDegree);
    };

    // Create buttons for each note
    ~buttons = ~notes.collect({ |note, i|
        Button(~win, Rect(10 + (i * 40), 10, 35, 100))
            .states_([[note.asString, Color.black, Color.white]])
            .mouseDownAction_({ ~playNote.(i) })
            .mouseUpAction_({ ~stopNote.(i) });
    });

    // Create a text field to display the sequence
    ~seqDisplay = TextView(~win, Rect(10, 120, 980, 100))
        .string_("Played sequence: ")
        .editable_(false);

    // Create buttons for various actions
    Button(~win, Rect(10, 230, 100, 30))
        .states_([["Clear Sequence"]])
        .action_({
            ~sequence.clear;
            ~seqDisplay.string_("Played sequence: ");
        });

    Button(~win, Rect(120, 230, 100, 30))
        .states_([["Print Sequence"]])
        .action_({
            var noteArray, durArray;
            noteArray = ~sequence.collect({ |item| item[0] });
            durArray = ~sequence.collect({ |item, i|
                if(item[1].isNil, {
                    0.5  // Default duration if no timestamp
                }, {
                    if(i == 0, {
                        0.5  // Default duration for the first note/chord
                    }, {
                        var prevTime = ~sequence[i-1][1];
                        if(prevTime.isNil, {
                            0.5  // Default duration if previous timestamp is missing
                        }, {
                            (item[1] - prevTime).max(0.01)  // Ensure positive duration
                        });
                    });
                });
            });
            "Note/Chord Array:".postln;
            noteArray.postln;
            "Duration Array:".postln;
            durArray.postln;
            "Pbind pattern:".postln;
            ("Pbind(\\degree, " ++ noteArray.collect({|item| item.asArray}).asCompileString ++
             ", \\dur, " ++ durArray.asCompileString ++ ")").postln;
        });

    Button(~win, Rect(230, 230, 100, 30))
        .states_([["Play Sequence"]])
        .action_({
            Routine({
                var prevTime = 0;
                ~sequence.do({ |item|
                    var degrees = item[0].asArray;
                    var time = item[1];
                    var synths;
                    if(time.notNil, {
                        (time - prevTime).wait;
                        prevTime = time;
                    }, {
                        0.5.wait;
                    });
                    synths = degrees.collect({ |degree|
                        var freq = (degree + 60).midicps;
                        Synth(\keyboardSynth, [\freq, freq, \amp, 0.5]);
                    });
                    AppClock.sched(0.2, { synths.do(_.set(\gate, 0)); nil });
                });
            }).play;
        });

    ~timingButton = Button(~win, Rect(340, 230, 150, 30))
        .states_([
            ["Start Timing Capture", Color.black, Color.green],
            ["Stop Timing Capture", Color.white, Color.red]
        ])
        .action_({ |but|
            if(but.value == 1, {
                ~capturingTime = true;
                startTime = Main.elapsedTime;
            }, {
                ~capturingTime = false;
            });
        });

    // Create buttons for octave shifting
    Button(~win, Rect(500, 230, 100, 30))
        .states_([["Octave Down"]])
        .action_({
            currentOctave = (currentOctave - 1).clip(-1, 7);
            ~updateOctaveDisplay.value;
        });

    Button(~win, Rect(610, 230, 100, 30))
        .states_([["Octave Up"]])
        .action_({
            currentOctave = (currentOctave + 1).clip(-1, 7);
            ~updateOctaveDisplay.value;
        });

    // Display current octave
    ~octaveDisplay = StaticText(~win, Rect(720, 230, 100, 30))
        .string_("Octave: 0")
        .align_(\center);

    ~updateOctaveDisplay = {
        ~octaveDisplay.string_("Octave: " ++ currentOctave);
    };

    // New button to activate/deactivate keyboard input
    Button(~win, Rect(830, 230, 150, 30))
        .states_([
            ["Activate Keyboard", Color.black, Color.green],
            ["Deactivate Keyboard", Color.white, Color.red]
        ])
        .action_({ |but|
            keyboardActive = but.value == 1;
            if(keyboardActive, {
                ~win.view.focus(true);
            });
        });

    // Update sequence display function
    ~updateSeqDisplay = {
        ~seqDisplay.string_("Played sequence: " ++ ~sequence.collect({ |item|
            var notes = item[0];
            var time = item[1];
            var noteStr = if(notes.isArray, {
                "[" ++ notes.collect(_.asString).join(", ") ++ "]"
            }, {
                notes.asString
            });
            if(time.isNil, {
                noteStr
            }, {
                noteStr ++ "@" ++ time.round(0.001).asString
            });
        }).join(", "));
    };

    // Set up a routine to periodically update the sequence display
    Routine({
        loop {
            ~updateSeqDisplay.();
            0.1.wait;
        }
    }).play(AppClock);

    // Add key responder
    ~win.view.keyDownAction = { |view, char, modifiers, unicode, keycode|
        if(keyboardActive, {
            var degree = ~keyboardMap[char.toLower];
            if(degree.notNil, {
                ~playNote.(degree);
            });
            // Number keys for octave selection
            if(char.isDecDigit, {
                var num = char.digit;
                currentOctave = num - 2;  // Shift range to be from -1 to 7
                currentOctave = currentOctave.clip(-1, 7);  // Limit range
                ~updateOctaveDisplay.value;
            });
        });
    };

    ~win.view.keyUpAction = { |view, char, modifiers, unicode, keycode|
        if(keyboardActive, {
            var degree = ~keyboardMap[char.toLower];
            if(degree.notNil, {
                ~stopNote.(degree);
            });
        });
    };
};

// Execute the function immediately
~createKeyboard.value;
)
raw 9566 chars (focus & ctrl+a+c to copy)
reception
comments