如何用Python编写MIDI文件?

时间:2012-06-16 00:37:27

标签: python midi

我正在编写一个脚本,根据各个像素的RGBA值将图片转换为MIDI音符。但是,我似乎无法完成最后一步,即实际将注释输出到文件。我曾尝试使用MIDIUtil库,但它的文档并不是最好的,我似乎无法弄明白。 如果有人能告诉我如何对音符进行排序(以便它们不是从一开始就开始),那将非常感激。

提前致谢。

2 个答案:

答案 0 :(得分:14)

查看示例,例如

from midiutil.MidiFile import MIDIFile

# create your MIDI object
mf = MIDIFile(1)     # only 1 track
track = 0   # the only track

time = 0    # start at the beginning
mf.addTrackName(track, time, "Sample Track")
mf.addTempo(track, time, 120)

# add some notes
channel = 0
volume = 100

pitch = 60           # C4 (middle C)
time = 0             # start on beat 0
duration = 1         # 1 beat long
mf.addNote(track, channel, pitch, time, duration, volume)

pitch = 64           # E4
time = 2             # start on beat 2
duration = 1         # 1 beat long
mf.addNote(track, channel, pitch, time, duration, volume)

pitch = 67           # G4
time = 4             # start on beat 4
duration = 1         # 1 beat long
mf.addNote(track, channel, pitch, time, duration, volume)

# write it to disk
with open("output.mid", 'wb') as outf:
    mf.writeFile(outf)

答案 1 :(得分:10)

我知道这是一篇旧帖子,但我是图书馆的作者,我想提一下现在已经统一了python 2和3支持,随着Google Code的消亡,代码现在托管在{ {3}}并且可以通过pip安装,即:

pip install MIDIUtil

文档位于GitHub

(试图评论,但我缺乏经验值。)

当文件写入磁盘时,会自动创建跟踪结束消息。