Growing Melodies

binary-sexEver since I heard about evolutionary programming, I’ve wanted to try it with music.  On a recent weekend, I finally did just that!

Some generated melodies are lovely in spurts but betray their purposlessness.  …Some just sound like Metroid on drugs.

The code is here: https://github.com/ology/Music/blob/master/bitstring-fitness

Update with less dependencies: https://github.com/ology/Music/blob/master/ai-genetic

Allow me to explain a bit… First we use a handy mutator:

I use bitstrings as notes in the scale.  So a bitstring of 11 bits (0 or 1) is the equivalent of an octave of the chromatic scale (i.e. C Cs D Ds E F G Gs A As B).  An example would be 10011010100 => C Ds E G A.

I mutate by toggling one bit at a time.  For each mutation, I pass the bitstring through a fitness function.  This looks at important things, like the presence of diatonic (“friendly”) scale notes, or the number of notes vs zeros.  This last insures that our melodies are not too short.

Now we have a scale of acceptable notes.  Next we pass them through an alteration phase that performs the actual “melodic” generation.  This uses the excellent module Music::AtonalUtil to perform a couple pitch gymnastics: retrograde motion, inversion, transposition and rotation.

Now we have our melody but it lacks any rhythmic variation.  Not to worry.  We grow rhythms in the very same way as pitches (well almost)!  Instead of note names, we use durations like “quarter note” or “triplet sixteenth.”

This can give your music either some “romantic flair” or possibly “Thelonius Monk type” random-walks. ;)

Example usage:

Play with your favorite MIDI player or use a DAW (Digital Audio Workstation) if you are fancy and want to alter the notes.  On OSX, GarageBand works fine for scratchpad experimentation.

Amazing! Fabulous! Brilliant!

You are now a computer music “composer.”

Here is a somewhat somber piece I put together with this code:

https://soundcloud.com/people-before-time/far-away-mountains

 

Comments

*