Random Music With Python

Posted on Fri 12 August 2016 in python

At PyCon 2016 I attended a very interesting session entitled Learning Python Through Music: JythonMusic & Pyknon, presented by Ria Baldevia. The talk was a great introduction to some python APIs that allow for the creation of music using the python language. Here I will demonstrate how to use the pyknon library, and some of the fun things one can do taking a programmatic approach to creating music.


pyknon is an easy-to-use tool that allows one to generate music with python code. Individual "Note" objects contain all the information needed to create a note, including pitch, and duration.

In [2]:
from pyknon.music import Note

C_note = Note(0, 5, dur=0.25) 

Here, I have instantiated a Note object, setting its pitch to middle C, and its duration to a quarter note. There is also a Rest class that allows one to create a musical rest.

In [3]:
from pyknon.music import Rest

quarter_rest = Rest(0.25) # quarter rest

One can also string together a sequence of notes using the NoteSeq class.

In [4]:
from pyknon.music import NoteSeq

A_note = Note(9, 5, 0.25)

# create a sequence of notes and rests
seq = NoteSeq([C_note, A_note, quarter_rest, C_note]) 

We can now write this sequence of notes to a midi file.

Throughout this post, I will be converting midi files to mp3 files so that one can listen back through their browser. I use garage band for this.

In [5]:
from pyknon.genmidi import Midi

midi = Midi(1, tempo=120)
midi.seq_notes(seq, track=0)
In [6]:
# I converted the midi file to a mp3 with garage band.
from IPython.display import Audio

So there you have it! A simple sequence of notes and rests that can be used to create individual music riffs. The pyknon API comes with many more cool features including the ability to create harmonies and chords. Though there is not a lot of documentation, the code is open source and very easy to read. There is also a book written by the author which describes the package in better detail.

When deciding how to utilize this tool, the first thing that came to mind was to randomly generate music. Specifically, I wanted to generate a sequence of randomly generated notes. I took the following approach to achieve this.

Given a set of pitches and a set of durations, randomly select a pitch, then a duration, and append it to an ongoing sequence of notes. For this exercise, I used the same octave for all notes.

The first step was to create a generic base track on top of which the randomly generated note sequences will sit. I used Garage Band to make a simple A power chord (5th chord) with an acoustic guitar preset. The generic nature of the power chord allows it to be paired with randomly generated note sequences in many different keys.

In [7]: