Python编写MIDI文件

2024-04-20 11:58:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用我从连接的数字钢琴接收的输入编写一个MIDI文件。我正在使用pygame.midi打开一个输入端口,并使用midiutil编写midi文件。我不能确定的是时间。例如,在addNote(track, channel, pitch, time, duration, volume)中,我如何知道音符的timeduration是什么?读笔记时,我的音高和音量都很好,但其他的我都不知道。。。我试着使用时间戳,但没有用,它把音符放在MIDI文件中很远的地方

那么,如何计算音符的“时间”和“持续时间”


Tags: 文件端口time时间channel数字trackpygame
1条回答
网友
1楼 · 发布于 2024-04-20 11:58:53

time指示音符在音乐时间中的位置。确切的参数应该是什么在一定程度上取决于Midi文件对象是如何构造的(稍后将详细介绍)

实际上,MIDI要求每个音符有两条消息:一条NOTE On消息和一条NOTE Off消息。duration将指示Note Off消息相对于便笺开头的发送时间。同样,参数的形成方式取决于文件对象的构造方式

MIDIUtil docs开始:

  • time – the time at which the note sounds. The value can be either quarter notes [Float], or ticks [Integer]. Ticks may be specified by passing eventtime_is_ticks=True to the MIDIFile constructor. The default is quarter notes.
  • duration – the duration of the note. Like the time argument, the value can be either quarter notes [Float], or ticks [Integer]

播放C大调音阶的完整示例

from midiutil import MIDIFile
degrees = [60, 62, 64, 65, 67, 69, 71, 72] # MIDI note number
track = 0
channel = 0
time = 0 # In beats
duration = 1 # In beats
tempo = 60 # In BPM
volume = 100 # 0-127, as per the MIDI standard
MyMIDI = MIDIFile(1) # One track, defaults to format 1 (tempo track
# automatically created)
MyMIDI.addTempo(track,time, tempo)
for pitch in degrees:
    MyMIDI.addNote(track, channel, pitch, time, duration, volume)
    time = time + 1
with open("major-scale.mid", "wb") as output_file:
    MyMIDI.writeFile(output_file)

将文件tempo(当前时间)与音符的位置(time)和duration(根据拍数)相结合,库可以合成在正确时间播放(开始/停止)音符所需的所有midi消息

另一个例子

让我们尝试将其应用于以下音乐短语:

musical phrase

首先,把一切都安排好

from midiutil import MIDIFile
track = 0
channel = 0
time = 0 # In beats
duration = 1 # In beats
tempo = 60 # In BPM
volume = 100 # 0-127, as per the MIDI standard
MyMIDI = MIDIFile(1) # One track, defaults to format 1 (tempo track
# automatically created)
MyMIDI.addTempo(track,time, tempo)

要在E上添加前半个音符,在G上添加四分之一个音符:

time = 0  # it's the first beat of the piece
quarter_note = 1  # equal to one beat, assuming x/4 time
half_note = 2 # Half notes are 2x value of a single quarter note
E3 = 64  # MIDI note value for E3
G3 = 67

# Add half note
MyMIDI.addNote(track, channel, pitch=E3, duration=half_note, time=0, volume=volume)
# Add quarter note
MyMIDI.addNote(track, channel, pitch=G3, duration=quarter_note, time=0, volume=volume)

现在,让我们添加其余注释:

A3 = 69
C3 = 60
B3 = 71
C4 = 72

# add the remaining notes
for time, pitch, duration in [(1,A3, quarter_note),
                              (2,B3, quarter_note), (2, C3, half_note), 
                              (3,C4, quarter_note)]:
    MyMIDI.addNote(track, channel, 
                   duration=duration, 
                   pitch=pitch, time=time, volume=volume)

相关问题 更多 >