Wednesday, February 24, 2016

10. Primary Triads in C

The three lists correspond to chords I, IV, and V, for key of 'C4'.


The purpose of addChord is to add a chord I, IV, or V, randomly, with the condition that that we have a change in chord.


The function randint from the standard random module, will generate a random integer within the given limits, and including those limits, that is, randint(0,2) can result in 0, 1 or 2.


The global variable num contains the last value indicating which chord was added. That is, num = 0 (chord I), num = 1, (chord IV), or num = 2 (chord V).


After each time, addChord() function is called it will calculate a new_num which is the value of randint(0,2). If it happens to be the same as last value (num), new_num is calculated again. This loop continues until the new_num is different from num. Then new_num replaces the value of num.


From now on, I will use a key of 'C' for the writeMIDI function. In the piano roll, the key does not matter, only on the score so it can put the appropriate sharps and flats.


# mus10.py
# Primary Triads in key of C

from writeMIDI import writeMIDI
from random import randint

# beats per minute
bpm = 130

tonic = ['C4','E4','G4']
subdominant = ['F4','A4','C5']
dominant = ['G4','B4','D5']

notes = []

start = -1
num = randint(0,2)

def addChord(n):
    global num
    global start
    start += 1
    print('num = {}'.format(num))
    if num == 0:
        for ch in tonic:
            n.append((ch,start,1,115))
    if num == 1:
        for ch in subdominant:
            n.append((ch,start,1,120))
    if num == 2:
        for ch in dominant:
            n.append((ch,start,1,125))
    new_num = randint(0,2)
    while new_num == num:
        new_num = randint(0,2)
    num = new_num
            
for i in range(20):
    addChord(notes)

writeMIDI('C','piano',bpm,notes,'mus10')

A possible output might be:

num = 0
num = 1
num = 2
num = 0
num = 2
num = 1
num = 2
num = 0
num = 1
num = 0
num = 2
num = 1
num = 2
num = 1
num = 2
num = 0
num = 2
num = 0
num = 2
num = 0

This will generate this:


No comments:

Post a Comment