I am using music21 to write midi file from the note values.
Following code writes three notes sequentially.
However, how do I insert an "empty" space between the notes?
It would be very easy if I could just insert the notes by their "position" so that I wouldn't have to calculate the position/length of each silent interval. Is that possible with music21?
import music21
from music21 import *
mt = midi.MidiTrack(1)
mt2 = midi.MidiTrack(1)
# duration, pitch, velocity
data = [[1024, 60, 90], [1024, 50, 70], [1024, 51, 120],[1024, 62, 80], ]
t=0
tLast=0
for d,p,v in data:
dt = midi.DeltaTime(mt)
dt.time = t-tLast
#add to track events
mt.events.append(dt)
me=midi.MidiEvent(mt)
me.type="NOTE_ON"
me.channel=1
me.time= None #d
me.pitch = p
me.velocity = v
mt.events.append(me)
# add note off / velocity zero message
dt = midi.DeltaTime(mt)
dt.time = d
# add to track events
mt.events.append(dt)
me=midi.MidiEvent(mt)
me.type="NOTE_ON"
me.channel=1
me.time= None #d
me.pitch = p
me.velocity = 0
mt.events.append(me)
tLast = t+d
t +=d
dt=midi.DeltaTime(mt)
dt.time = 0
mt.events.append(dt)
me = midi.MidiEvent(mt)
me.type = "END_OF_TRACK"
me.channel = 1
me.data ='' # must set data to empty string
mt.events.append(me)
mf = midi.MidiFile()
mf.ticksPerQuarterNote = 1024 # cannot use: 10080
mf.tracks.append(mt)
mf.tracks.append(mt2)
mf.open('test.mid', 'wb')
mf.write()
mf.close()
In a MIDI file, all events are preceded by a delta time value that specifies how long to wait from the last event.
In your code,
t
andtLast
are both increased by the note's duration, so there is no pause between a note off and the following note on.If you want the next note to start later, you have to increase
t
by a larger amount.