Trying to generate a random sequence of notes in two voices with music21.
The second voice should be transposed from the (random) first voice.
It seems that the transpose octaves some of the notes.
Maybe there is something wrong in my code, but I cannot find the error.
Does the transpose function limit the range?
Or what else could be the reason that the result is not a second voice
transposed a perfect forth (the line in comment is alternately transposing
an octave, this also does not work correct).
from music21 import *
import random
score = stream.Score()
part = stream.Part()
piano = instrument.Piano()
print(f"type of piano: {type(piano)}")
part.insert(0,piano)
voice1 = stream.Voice()
voice2 = stream.Voice()
notes = ['C4', 'D4', 'E4', 'F4', 'G4', 'A4', 'B4', 'C5', 'D5', 'E5', 'F5', 'G5', 'A5', 'B5', 'C6']
nNotes = len(notes)
def getSeq(seqLen):
seq = []
for i in range(0,seqLen):
restart = 1
last = -1
while (restart == 1):
noteIdx = random.randint(1,nNotes-1)
if (noteIdx != last):
restart = 0
aNote = note.Note(notes[noteIdx])
seq.append(aNote)
last = noteIdx
upDown = random.randint(0,1);
if (upDown == 0):
#print("up from :" , noteIdx)
nextIdx = noteIdx - 1
else:
#print("down from" , noteIdx)
nextIdx = noteIdx - 1
if (nextIdx > seqLen):
nextIdx = nextIdx - 12
if (nextIdx<0):
nextIdx = nextIdx + 12
nextNote = note.Note(notes[nextIdx])
seq.append(nextNote)
return seq
voiceLength = 5
for i in range (0,voiceLength):
seqLen = 1
seq = getSeq(seqLen)
seq2 = []
print(f"seq: (i = {i})")
for s in seq:
print(str(s) + " " + str(s.octave))
voice1.append(s)
s2 = note.Note(s.name)
print(f"s2 = {s2}")
seq2.append(s2)
for s in seq2:
sx = s.transpose('P4')
#sx = s.transpose(12)
voice2.append(sx)
part.insert(0, voice1)
part.insert(1, voice2)
print ("voice 1 -------------------------------")
for x in voice1:
print(f"name: {x.name}")
print ("voice 2 -------------------------------")
for x in voice2:
print (f"{x}")
score.insert(0, part)
score.show()
”’
output (with musescore3):