如何在music21序列中保持偏移?

问题描述 投票:0回答:1

此函数应该用两个具有相同值但持续时间一半的音符替换序列中的一个音符:

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

但是我的两个新音符永远不会落在计算的偏移处,而是落在其他地方。我做错了什么?

python-3.x music21
1个回答
0
投票

在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 将它们插入到最后设置的偏移量处。

© www.soinside.com 2019 - 2024. All rights reserved.