Skip to main content

Article

Generating music with F# part 2: Markov chains

Minna Kaitala

March 29, 2015


Continuing from the previous post.

To make melody generation more interesting I decided to try applying statistical process called Markov chain. In the context of this post by Markov chain I mean that the next state of the system is not completely random but next states have different probabilities that depend on the current state.

There is a Finnish children’s song and a Swedish drinking song called “Ukko-Nooa” or “Gubben Noak” that has a simple melody that goes like this:

We create a map of notes to sequence of notes. Sequence consists of notes that can follow the note that is used as key.

This is how to get next random note based on current note.

The more times a note is contained in the sequence where currentNote acts as a key, the more likely it is to become next note.

Rest of the program looks like this:

nextNoteFromData is partially applied function of getNextNote that can be used without passing an instance of System.Random along. randomMelody recursively creates list of notes until given length is achieved.

That’s it! Here is an example of the output. Much better than the completely random version from previous post.

The full source code is on GitHub