这是我的代码:
import midi
pattern = midi.read_midifile('midifile.mid')
for p in pattern:
for event, lastEvent in zip(p[1:], p):
if event.name == 'Note On' and lastEvent.name == 'Note On':
if event.channel == 1:
print(event.pitch, lastEvent.pitch)
举个例子,前5个音高是57, 45, 65, 53, 52
我想要的意思
45, 57
65, 45
53, 65
52, 53
但代码的输出是
45, 57
53, 65
64, 52
50, 62
提前致谢
答案 0 :(得分:1)
我认为问题在于.name
属性是否全部'Note on'
这意味着您要将事件与之前的事件进行比较,而不是之前的事件event.name == 'Note on'
也许试试:
import midi
pattern = midi.read_midifile('midifile.mid')
for p in pattern:
previous_event = p[0]
for event in p[1:]:
if event.name == 'Note on':
if event.channel == 1:
print(event.pitch, previous_event.pitch)
previous_event = event
我尝试做的是过滤p中的事件,仅针对那些使用event.name =='注意' (尽管我确定有更简单的方法可以通过p = [event for event in p if event.name == 'Note on']
包含这样的意思:
import midi
pattern = midi.read_midifile('midifile.mid')
for p in pattern:
p2 = [event for event in p if event.name == 'Note on'] # maybe should include and event.channel ==1 ?
for event, lastEvent in zip(p2[1:], p2):
if event.name == 'Note On' and lastEvent.name == 'Note On':
if event.channel == 1:
print(event.pitch, lastEvent.pitch)