Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python MIDI libraries read and write MIDI files and exchange MIDI messages with instruments and software in real time. A file library edits the notes and timing stored in a file rather than the live messages that a port library sends to connected devices. These libraries let music apps and AI music models read and generate notes as data.
Popularity
Mido has the most monthly downloads among the dedicated MIDI libraries in this comparison, at 1.4M.
def _open(self, **kwargs):
if kwargs.get('virtual'):
raise ValueError('virtual ports are not supported'
' by the Pygame backend')
elif kwargs.get('callback'):
raise ValueError('callbacks are not supported'
' by the Pygame backend')
midi.init()
if self.name is None:
device = _get_default_device(self.is_input)
self.name = device['name']
else:
device = _get_named_device(self.name, self.is_input)
if device['opened']:
if self.is_input:
devtype = 'input'
else:
devtype = 'output'
raise OSError('{} port {!r} is already open'.format(devtype,
self.name))
if self.is_input:
self._port = midi.Input(device['id'])
else:
self._port = midi.Output(device['id'])
self._device_type = 'Pygame/{}'.format(device['interface'])
Mido
Reads and writes MIDI messages and files, with a shared interface for live ports and backends.
Downloads / mo
1.4M
Stars
1.7K
Last release
1.3.3
License
MIT
Strengths
Exposes individual MIDI messages.Reads, edits, and writes messages, including common meta events.
Connects live MIDI ports.Choose a backend to send and receive real-time MIDI messages.
Limitations
Timing depends on the context.File tracks use tick deltas; file iteration returns elapsed seconds.
Independent tracks lack shared length.Asynchronous files cannot use the total playback-length property.
def _m21Parse(f, fmt=None, remove_perc=True):
"""
Parameters
---------- f :
fmt :
(Default value = None)
Returns
------- """
import music21
s = music21.converter.parse(f, format=fmt, forceSource=True)
if remove_perc:
for el in s.recurse():
if set(el.classes).intersection(['PercussionChord', 'Unpitched']): # or 'Piano'
# el.activeSite.replace(el, instrument.Violin()) el.activeSite.remove(el)
# perc = [ # p # for p in s.parts # if list(p.recurse().getElementsByClass(["PercussionClef", "PercussionChord"])) # ] # s.remove(perc, recurse=True) return s
pretty_midi
Represents MIDI notes and instruments with second-based timing for analysis, editing, and synthesis.
Downloads / mo
692.7K
Stars
1.0K
Last release
0.2.11.post0
License
MIT
Strengths
Uses seconds for note timing.Edit note start and end times directly in seconds.
Synthesizes sine-wave previews.Generate a sine-wave audio array with synthesize.
Limitations
Instrument synthesis needs external packages.Install FluidSynth and pyfluidsynth for instrument-based synthesis.
Sine synthesis skips drum sounds.Instrument.synthesize returns silence for drum instruments.
def note_events_to_midi(
note_events_with_pitch_bends: List[Tuple[float, float, int, float, Optional[List[int]]]],
multiple_pitch_bends: bool = False,
midi_tempo: float = 120,
) -> pretty_midi.PrettyMIDI:
"""Create a pretty_midi object from note events
Args:
note_events : list of tuples [(start_time_seconds, end_time_seconds, pitch_midi, amplitude)]
where amplitude is a number between 0 and 1
multiple_pitch_bends : If True, allow overlapping notes to have pitch bends
Note: this will assign each pitch to its own midi instrument, as midi does not yet
support per-note pitch bends
Returns:
pretty_midi.PrettyMIDI() object
"""
mid = pretty_midi.PrettyMIDI(initial_tempo=midi_tempo)
if not multiple_pitch_bends:
note_events_with_pitch_bends = drop_overlapping_pitch_bends(note_events_with_pitch_bends)
piano_program = pretty_midi.instrument_name_to_program("Electric Piano 1")
instruments: DefaultDict[int, pretty_midi.Instrument] = defaultdict(
lambda: pretty_midi.Instrument(program=piano_program)
)
for start_time, end_time, note_number, amplitude, pitch_bend in note_events_with_pitch_bends:
instrument = instruments[note_number] if multiple_pitch_bends else instruments[0]
note = pretty_midi.Note(
velocity=int(np.round(MIDI_VELOCITY_SCALE * amplitude)),
pitch=note_number,
start=start_time,
end=end_time,
)
instrument.notes.append(note)
if not pitch_bend:
continue
pitch_bend_times = np.linspace(start_time, end_time, len(pitch_bend))
pitch_bend_midi_ticks = np.round(np.array(pitch_bend) * PITCH_BEND_SCALE / CONTOURS_BINS_PER_SEMITONE).astype(
int
)
# This supports pitch bends up to 2 semitones # If we estimate pitch bends above/below 2 semitones, crop them here when adding them to the midi file pitch_bend_midi_ticks[pitch_bend_midi_ticks > N_PITCH_BEND_TICKS - 1] = N_PITCH_BEND_TICKS - 1
pitch_bend_midi_ticks[pitch_bend_midi_ticks < -N_PITCH_BEND_TICKS] = -N_PITCH_BEND_TICKS
for pb_time, pb_midi in zip(pitch_bend_times, pitch_bend_midi_ticks):
instrument.pitch_bends.append(pretty_midi.PitchBend(pb_midi, pb_time))
mid.instruments.extend(instruments.values())
return mid
Symusic
Parses MIDI files through a high-performance interface.
def get_devices(api=None, **kwargs):
devices = {}
rtapi = _get_api_id(api)
mi = rtmidi.MidiIn(rtapi=rtapi)
mo = rtmidi.MidiOut(rtapi=rtapi)
input_names = mi.get_ports()
output_names = mo.get_ports()
for name in input_names + output_names:
if name not in devices:
devices[name] = {
'name': name,
'is_input': name in input_names,
'is_output': name in output_names,
}
mi.delete()
mo.delete()
return list(devices.values())
MIDIUtil
Creates multitrack MIDI files from note, tempo, controller, and other event definitions.
Downloads / mo
41.3K
Stars
273
Last release
1.2.1
License
MIT
Strengths
Writes multitrack MIDI files directly.Build tracks by adding note and tempo events before writing the file.
Adds controller and system events.Write controller, SysEx, and registered-parameter events alongside notes.
Limitations
Ticks require an explicit mode.Set eventtime_is_ticks when passing native MIDI tick values.
Tempo uses the dedicated track.Format-one files ignore the requested track for tempo events.
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
MyMIDI.addTempo(track, time, tempo)
for i, pitch in enumerate(degrees):
MyMIDI.addNote(track, channel, pitch, time + i, duration, volume)
with open("major-scale.mid", "wb") as output_file:
MyMIDI.writeFile(output_file)
def pianoroll_to_midi(bpm: float, pianoroll: list) -> midiutil.MIDIFile():
"""
Converts an internal piano roll notation to a MIDI file
Parameters
---------- bpm: float
Beats per minute for the MIDI file. If necessary, use
bpm = librosa.beat.tempo(y)[0] to estimate bpm.
pianoroll : list
A pianoroll list as estimated by states_to_pianoroll().
Returns
------- None.
"""
quarter_note = 60 / bpm
onsets = np.array([p[0] for p in pianoroll])
offsets = np.array([p[1] for p in pianoroll])
onsets = onsets / quarter_note
offsets = offsets / quarter_note
durations = offsets - onsets
midi = midiutil.MIDIFile(1)
midi.addTempo(0, 0, bpm)
for i, _ in enumerate(onsets):
midi.addNote(
0, 0, int(pianoroll[i][2]), onsets[i], durations[i], 100)
return midi
Miditoolkit
Edits MIDI instruments and events in native ticks and converts notes to piano-roll grids.
Downloads / mo
23.6K
Stars
285
Last release
1.0.1
License
MIT
Strengths
Edits notes in native ticks.Work with integer MIDI timing instead of second-based note positions.
Produces piano-roll note grids.Convert notes to time-and-pitch grids for analysis or visualization.
Limitations
Note timing stays in ticks.Convert ticks before comparing note positions with audio timestamps.
def write_midi(words, word2event, output_path, prompt_path=None):
events = word_to_event(words, word2event)
# get downbeat and note (no time) temp_notes = []
temp_chords = []
temp_tempos = []
for i in range(len(events)-3):
if events[i].name == 'Bar' and i > 0:
temp_notes.append('Bar')
temp_chords.append('Bar')
temp_tempos.append('Bar')
elif events[i].name == 'Position' and \
events[i+1].name == 'Note Velocity' and \
events[i+2].name == 'Note On' and \
events[i+3].name == 'Note Duration':
# start time and end time from position position = int(events[i].value.split('/')[0]) - 1
# velocity index = int(events[i+1].value)
velocity = int(DEFAULT_VELOCITY_BINS[index])
# pitch pitch = int(events[i+2].value)
# duration index = int(events[i+3].value)
duration = DEFAULT_DURATION_BINS[index]
# adding temp_notes.append([position, velocity, pitch, duration])
elif events[i].name == 'Position' and events[i+1].name == 'Chord':
position = int(events[i].value.split('/')[0]) - 1
temp_chords.append([position, events[i+1].value])
elif events[i].name == 'Position' and \
events[i+1].name == 'Tempo Class' and \
events[i+2].name == 'Tempo Value':
position = int(events[i].value.split('/')[0]) - 1
if events[i+1].value == 'slow':
tempo = DEFAULT_TEMPO_INTERVALS[0].start + int(events[i+2].value)
elif events[i+1].value == 'mid':
tempo = DEFAULT_TEMPO_INTERVALS[1].start + int(events[i+2].value)
elif events[i+1].value == 'fast':
tempo = DEFAULT_TEMPO_INTERVALS[2].start + int(events[i+2].value)
temp_tempos.append([position, tempo])
# get specific time for notes ticks_per_beat = DEFAULT_RESOLUTION
ticks_per_bar = DEFAULT_RESOLUTION * 4 # assume 4/4
notes = []
current_bar = 0
for note in temp_notes:
if note == 'Bar':
current_bar += 1
else:
position, velocity, pitch, duration = note
# position (start time) current_bar_st = current_bar * ticks_per_bar
current_bar_et = (current_bar + 1) * ticks_per_bar
flags = np.linspace(current_bar_st, current_bar_et, DEFAULT_FRACTION, endpoint=False, dtype=int)
st = flags[position]
# duration (end time) et = st + duration
notes.append(miditoolkit.Note(velocity, pitch, st, et))
# get specific time for chords if len(temp_chords) > 0:
chords = []
current_bar = 0
for chord in temp_chords:
if chord == 'Bar':
current_bar += 1
else:
position, value = chord
# position (start time) current_bar_st = current_bar * ticks_per_bar
current_bar_et = (current_bar + 1) * ticks_per_bar
flags = np.linspace(current_bar_st, current_bar_et, DEFAULT_FRACTION, endpoint=False, dtype=int)
st = flags[position]
chords.append([st, value])
# get specific time for tempos tempos = []
current_bar = 0
for tempo in temp_tempos:
if tempo == 'Bar':
current_bar += 1
else:
position, value = tempo
# position (start time) current_bar_st = current_bar * ticks_per_bar
current_bar_et = (current_bar + 1) * ticks_per_bar
flags = np.linspace(current_bar_st, current_bar_et, DEFAULT_FRACTION, endpoint=False, dtype=int)
st = flags[position]
tempos.append([int(st), value])
# write if prompt_path:
midi = miditoolkit.midi.parser.MidiFile(prompt_path)
# last_time = DEFAULT_RESOLUTION * 4 * 4
# note shift for note in notes:
note.start += last_time
note.end += last_time
midi.instruments[0].notes.extend(notes)
# tempo changes temp_tempos = []
for tempo in midi.tempo_changes:
if tempo.time < DEFAULT_RESOLUTION*4*4:
temp_tempos.append(tempo)
else:
break
for st, bpm in tempos:
st += last_time
temp_tempos.append(miditoolkit.midi.containers.TempoChange(bpm, st))
midi.tempo_changes = temp_tempos
# write chord into marker if len(temp_chords) > 0:
for c in chords:
midi.markers.append(
miditoolkit.midi.containers.Marker(text=c[1], time=c[0]+last_time))
else:
midi = miditoolkit.midi.parser.MidiFile()
midi.ticks_per_beat = DEFAULT_RESOLUTION
# write instrument inst = miditoolkit.midi.containers.Instrument(0, is_drum=False)
inst.notes = notes
midi.instruments.append(inst)
# write tempo tempo_changes = []
for st, bpm in tempos:
tempo_changes.append(miditoolkit.midi.containers.TempoChange(bpm, st))
midi.tempo_changes = tempo_changes
# write chord into marker if len(temp_chords) > 0:
for c in chords:
midi.markers.append(
miditoolkit.midi.containers.Marker(text=c[1], time=c[0]))
# write midi.dump(output_path)
FAQ
Mido suits most work with MIDI messages, files, and device ports. pretty_midi suits analysis of notes and instruments with times in seconds. music21 suits music analysis that treats MIDI as a score.
Mido works with MIDI messages, MIDI files, and real-time ports through selectable backends.
Mido reads a MIDI file as tracks of messages with timing in ticks. pretty_midi reads the same file as instruments and notes with times in seconds.
MIDIUtil creates multi-track MIDI files from note and tempo events in pure Python. It writes files only and does not read them or connect to live ports.
For coding agents
Found your MIDI library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.