此函数应该用两个具有相同值但持续时间一半的音符替换序列中的一个音符:
def double_note(mystream):
random_index = randint(0, (len(mystream) - 1))
if len(mystream.getElementsByClass(note.Note)) > 0 and isinstance(mystream[random_index], note.Note):
selected_note = mystream[random_index]
# Create two new notes of half the duration
new_note1 = note.Note(selected_note.pitch, quarterLength=selected_note.duration.quarterLength / 2)
new_note2 = note.Note(selected_note.pitch, quarterLength=selected_note.duration.quarterLength / 2)
# Adjust offsets of the new notes
new_note1.offset = selected_note.offset
new_note2.offset = selected_note.offset + new_note1.duration.quarterLength
print(selected_note, selected_note.duration.quarterLength)
print(new_note1.offset, new_note2.offset)
# Replace the selected note in the sequence with the two new notes
mystream.pop(random_index)
mystream.insert(random_index, new_note1)
mystream.insert(random_index + 1, new_note2)
else:
pass
return mystream
但是我的两个新音符永远不会落在计算的偏移处,而是落在其他地方。我做错了什么?
在music21中,
insert
根据偏移量工作,而不是根据流中的索引(0,1,2,...)。所以你应该替换这些行:
mystream.pop(random_index)
mystream.insert(random_index, new_note1)
mystream.insert(random_index + 1, new_note2)
与
mid_duration
mystream.remove(selected_note)
mystream.insert(new_note1)
mystream.insert(new_note2)
通过设置 new_note1 + 2 的正确新偏移量,您将告诉 music21 将它们插入到最后设置的偏移量处。