Using Arrays with ChucK
ChucK is an on the fly audio programming language which can be used to create improvised music and audio. I covered the basic steps to start using ChucK in my last post. In this post I wanted to touch on a question I was asked around using Arrays to create music.
An array is an object that can be used to store multiple values in a single variable. This is useful when you want to play a number of notes without having to write excessive amounts of code. Take a look at the code below:
StifKarp s => dac; Std.mtof( 48 + 0 ) => s.freq; s.noteOn( 0.5 ); 300::ms => now; Std.mtof( 48 + 2 ) => s.freq; s.noteOn( 0.5 ); 300::ms => now; Std.mtof( 48 + 4 ) => s.freq; s.noteOn( 0.5 ); 300::ms => now; Std.mtof( 48 + 7 ) => s.freq; s.noteOn( 0.5 ); 300::ms => now; Std.mtof( 48 + 9 ) => s.freq; s.noteOn( 0.5 ); 300::ms => now; Std.mtof( 48 + 11 ) => s.freq; s.noteOn( 0.5 ); 300::ms => now;
This will play a sequence of notes – but doing it this way uses a lot of code. Using an array will reduce the amount of code required but still produce the same sequence of notes.
In order to use an array you need to first create it:
[ 0, 2, 4, 7, 9, 11 ] @=> int notes[];
The above code adds the numbers 0, 2, 4, 7, 9 and 11 to the array. Data in the array can be accessed using the index number.
Std.mtof(48 + notes[3]) => s.freq;
is the same as
Std.mtof(48 + 4) => s.freq;
But this still doesn’t reduce the amount of code we are writing. The key to this is to loop through the array and play all of the notes stored within the variable.
for(initialization; Boolean_expression; update)
The above code creates a for loop. A loop needs to be initialized, it needs to know how long to loop for and it needs to know what to update.
for(0 => int i; i < notes.cap(); i++){
In order for us to loop through the notes I’ve created a new variable called i. This will be used to control the loop. The initialization sets the i variable to 0. We then need to tell ChucK how long to loop for. In the example above the loop will continue until i = the total number of variables in the notes array. Finally we tell ChucK to increase i by 1 each time the loop is updated.
Once the loop is complete you can add the code to produce the notes. Within this we use the array to specify which note is played:
StifKarp s => dac;
[ 0, 2, 4, 7, 9, 11 ] @=> int notes[];
for(0 => int i; i < notes.cap(); i++){
Std.mtof( 48 + notes[i%notes.cap()] ) => s.freq;
s.noteOn( 0.5 );
300::ms => now;
}
Hopefully this gives you a brief introduction to Arrays and loops. Feel free to post any questions in the comments below.
Google+
