How to build an Arpeggiator

It’s been far too long since I blogged. I’ve been super immersed in my first job as a RoR developer at Custom Solutions Group and making music. As it turns out, I’m bringing my two most urgent passions, coding and songwriting, together.

For an upcoming performance at my friend’s salon in Brooklyn, NY, I’m weaving the leitmotif from the 1992 film Cape Fear into my set using an online synth and a simple script I wrote to introduce the theme.

The script relies on the js setTimeout() function to execute code after a delay of 950 milliseconds. The delay allows a note to continue playing until the next time the script fires.

After inspecting the synth’s source code, I discovered I could call its keyUp() and keyDown() functions to automate playback. The tricky part was tracking which notes to keyup or keydown, and when to use a delay between notes or not. To achieve seamless playback, I store the arpeggio notes in an array, and use the index to identify which note in the arpeggio should be keyed up or down; in other words, the current and previous note, or i and i-1.

As well, I use a counter, independent of any particular arpeggio, to measure total notes played. In this example, I limit the program to play 10 arpeggios consecutively for a total of 40 notes (see line 25), at which point the program terminates.

Most important, when the remainder of the counter % 4 is 0, the last note in the current arpeggio has been played (it will always be a multiple of 4). At that point, I reset the index to 0 and use a callback to restart the code and play the first note in the arpeggio without a delay to avoid a gap between arpeggios.

Here’s the code! Have fun and give it a try. Just follow the instructions up top. Coding gives you semi-super powers to do beautiful things.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s