# Python MIDI libraries

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

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [pygame](#pygame) | 2.7M | 9.0K | Sep 2024 | GNU Library or Lesser General Public License (LGPL) |
| [Mido](#mido) | 1.4M | 1.7K | Oct 2024 | MIT |
| [music21](#musictwoone) | 950.0K | 2.6K | Oct 2026 | BSD |
| [pretty_midi](#pretty-midi) | 692.7K | 1.0K | Jul 2026 | MIT |
| [Symusic](#symusic) | 461.4K | 190 | Apr 2026 | MIT |
| [python-rtmidi](#python-rtmidi) | 203.0K | 417 | Nov 2023 | MIT |
| [MIDIUtil](#midiutil) | 41.3K | 273 | Mar 2018 | MIT |
| [Miditoolkit](#miditoolkit) | 23.6K | 285 | Nov 2023 | MIT |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[Mido](#mido) has the most monthly downloads among the dedicated MIDI libraries in this comparison, at 1.4M.

## Capabilities

| Library | Parses MIDI files | Opens MIDI ports |
| --- | --- | --- |
| [pygame](#pygame) | No | Yes |
| [Mido](#mido) | Yes | Yes |
| [music21](#musictwoone) | Yes | No |
| [pretty_midi](#pretty-midi) | Yes | No |
| [Symusic](#symusic) | Yes | No |
| [python-rtmidi](#python-rtmidi) | No | Yes |
| [MIDIUtil](#midiutil) | No | No |
| [Miditoolkit](#miditoolkit) | Yes | No |

## Libraries

### pygame

[GitHub](https://github.com/pygame/pygame) · [PyPI](https://pypi.org/project/pygame) · [Docs](https://www.pygame.org/docs/ref/midi.html)

Supports game development in Python.

- Downloads / mo: 2.7M
- Stars: 9.0K
- Last release: 2.6.1
- License: GNU Library or Lesser General Public License (LGPL)
- Capabilities: [From the pygame docs](https://www.pygame.org/docs/ref/midi.html)

```sh
python3 -m pip install pygame
```

**mido/mido** (1.7K stars)

[mido/mido](https://github.com/mido/mido) 

```python
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/backends/pygame.py](https://github.com/mido/mido/blob/d261ee41db32717fb73dfaa14162159fb6529ef5/mido/backends/pygame.py#L71-L99) · [More projects using pygame →](https://dashboard.exa.ai/playground/search?q=pygame%20GitHub%20projects)

**Quickstart**

```python
import pygame.midi
pygame.midi.init()
pygame.midi.get_count()
pygame.midi.quit()

```

From [midi.html](https://www.pygame.org/docs/ref/midi.html)

### Mido

[GitHub](https://github.com/mido/mido) · [PyPI](https://pypi.org/project/mido) · [Docs](https://github.com/mido/mido/blob/main/README.rst)

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
- Capabilities: [From the Mido docs](https://github.com/mido/mido/blob/main/README.rst)

**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.

**Watch out for**

- **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.

```sh
python3 -m pip install mido
```

**magenta/magenta** (19.8K stars)

[magenta/magenta](https://github.com/magenta/magenta) 

```python
def run(self):
  """Sends message on the qpm interval until stop signal received."""
  sleeper = concurrency.Sleeper()
  while True:
    now = time.time()
    tick_number = max(0, int((now - self._start_time) // self._period) + 1)
    tick_time = tick_number * self._period + self._start_time

    if self._stop_time is not None and self._stop_time < tick_time:
      break

    sleeper.sleep_until(tick_time)

    metric_position = tick_number % len(self._messages)
    tick_message = self._messages[metric_position]

    if tick_message is None:
      continue

    tick_message.channel = self._channel
    self._outport.send(tick_message)

    if tick_message.type == 'note_on':
      sleeper.sleep(self._duration)
      end_tick_message = mido.Message(
          'note_off', note=tick_message.note, channel=self._channel)
      self._outport.send(end_tick_message)

```

[magenta/interfaces/midi/midi_hub.py](https://github.com/magenta/magenta/blob/c15687ebd1c1cc12658cd468c737d3c24c02b918/magenta/interfaces/midi/midi_hub.py#L239-L265) · [More projects using Mido →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20mido%20for%20live%20metronome%20scheduling%2C%20pitch-bend%20note%20conversion%20and%20generated%20music-file%20writing&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import mido
msg = mido.Message('note_on', note=60)
msg.bytes()

```

From [create_midi_file.py](https://github.com/mido/mido/blob/main/README.rst)

### music21

[GitHub](https://github.com/cuthbertLab/music21) · [PyPI](https://pypi.org/project/music21) · [Docs](https://pypi.org/pypi/music21/10.5.2/json)

Analyzes music with tools for computational musicology.

- Downloads / mo: 950.0K
- Stars: 2.6K
- Last release: 10.5.2
- License: BSD
- Capabilities: [From the music21 docs](https://pypi.org/pypi/music21/10.5.2/json)

```sh
python3 -m pip install music21
```

**MusicLang/musiclang** (207 stars)

[MusicLang/musiclang](https://github.com/MusicLang/musiclang) 

```python
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

```

[musiclang/analyze/parser.py](https://github.com/MusicLang/musiclang/blob/6d1f4afc88cdbc7be3635862cafd980e41e77f67/musiclang/analyze/parser.py#L640-L669) · [More projects using music21 →](https://dashboard.exa.ai/playground/search?q=music21%20GitHub%20projects)

**Quickstart**

```python
from music21 import converter
score = converter.parse('example.mid', format='midi')

```

From [moduleConverter.html](https://www.music21.org/music21docs/moduleReference/moduleConverter.html)

### pretty_midi

[GitHub](https://github.com/craffel/pretty-midi) · [PyPI](https://pypi.org/project/pretty_midi) · [Docs](https://craffel.github.io/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
- Capabilities: [From the pretty_midi docs](https://craffel.github.io/pretty-midi/)

**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.

**Watch out for**

- **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.

```sh
python3 -m pip install pretty_midi
```

**spotify/basic-pitch** (6.1K stars)

[spotify/basic-pitch](https://github.com/spotify/basic-pitch) 

```python
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

```

[basic_pitch/note_creation.py](https://github.com/spotify/basic-pitch/blob/fa5997af0a8210982619003269994a1be25eddf3/basic_pitch/note_creation.py#L222-L271) · [More projects using pretty_midi →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20pretty_midi%20for%20live%20metronome%20scheduling%2C%20pitch-bend%20note%20conversion%20and%20generated%20music-file%20writing&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import pretty_midi
midi_data = pretty_midi.PrettyMIDI('example.mid')
print(midi_data.estimate_tempo())

```

From [README.md](https://craffel.github.io/pretty-midi/)

### Symusic

[GitHub](https://github.com/Yikai-Liao/symusic) · [PyPI](https://pypi.org/project/symusic) · [Docs](https://api.github.com/repos/Yikai-Liao/symusic/contents/README.md)

Parses MIDI files through a high-performance interface.

- Downloads / mo: 461.4K
- Stars: 190
- Last release: 0.6.0
- License: MIT
- Capabilities: [From the Symusic docs](https://api.github.com/repos/Yikai-Liao/symusic/contents/README.md)

```sh
python3 -m pip install symusic
```

**Natooz/MidiTok** (908 stars)

[Natooz/MidiTok](https://github.com/Natooz/MidiTok) 

```python
def _augment_dataset_inner(
    file_path: Path,
    data_path: Path,
    pitch_offsets: list[int] | None = None,
    velocity_offsets: list[int] | None = None,
    duration_offsets: list[int] | None = None,
    all_offset_combinations: bool = False,
    restrict_on_program_tessitura: bool = True,
    velocity_range: tuple[int, int] = (1, 127),
    duration_in_ticks: bool = False,
    min_duration: float = 0.03125,
    out_path: Path | str | None = None,
    copy_original_in_new_location: bool = True,
) -> tuple[int, int] | tuple[0, 0]:

    num_augmentations, num_tracks_augmented = 0, 0
    try:
        score = Score(file_path)
    except SCORE_LOADING_EXCEPTION:
        return num_augmentations, num_tracks_augmented

    augmented_scores = augment_score_multiple_offsets(
        score,
        pitch_offsets,
        velocity_offsets,
        duration_offsets,
        all_offset_combinations,
        restrict_on_program_tessitura,
        velocity_range,
        duration_in_ticks,
        min_duration,
    )
    for aug_offsets, score_aug in augmented_scores:
        if len(score_aug.tracks) == 0:
            continue
        suffix = "#" + "_".join(
            [
                f"{t}{offset}"
                for t, offset in zip(["p", "v", "d"], aug_offsets, strict=False)
                if offset != 0
            ]
        )
        saving_path = out_path / file_path.parent.relative_to(data_path)
        saving_path.mkdir(parents=True, exist_ok=True)
        saving_path /= f"{file_path.stem}{suffix}{file_path.suffix}"
        if file_path.suffix in MIDI_FILES_EXTENSIONS:
            score_aug.dump_midi(saving_path)
        else:
            score_aug.dump_abc(saving_path)
        num_augmentations += 1
        num_tracks_augmented += len(score_aug.tracks)

    if copy_original_in_new_location and out_path != data_path:
        saving_path = out_path / file_path.relative_to(data_path)
        saving_path.parent.mkdir(parents=True, exist_ok=True)
        copy2(file_path, saving_path)

    return num_augmentations, num_tracks_augmented

```

[src/miditok/data_augmentation/data_augmentation.py](https://github.com/Natooz/MidiTok/blob/680b5a4ec1b2ebd2e55f229ffcfce7f4770a2411/src/miditok/data_augmentation/data_augmentation.py#L186-L243) · [More projects using Symusic →](https://dashboard.exa.ai/playground/search?q=symusic%20GitHub%20projects)

**Quickstart**

```python
from symusic import Score
score = Score("example.mid")         # format auto-detected

```

From [quickstart.html](https://symusic.readthedocs.io/en/stable/quickstart.html)

### python-rtmidi

[GitHub](https://github.com/SpotlightKid/python-rtmidi) · [PyPI](https://pypi.org/project/python-rtmidi) · [Docs](https://api.github.com/repos/SpotlightKid/python-rtmidi/contents/README.md)

Binds the RtMidi C++ library to Python with Cython.

- Downloads / mo: 203.0K
- Stars: 417
- Last release: 1.5.8
- License: MIT
- Capabilities: [From the python-rtmidi docs](https://api.github.com/repos/SpotlightKid/python-rtmidi/contents/README.md)

```sh
python3 -m pip install python-rtmidi
```

**mido/mido** (1.7K stars)

[mido/mido](https://github.com/mido/mido) 

```python
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())
```

[mido/backends/rtmidi.py](https://github.com/mido/mido/blob/d261ee41db32717fb73dfaa14162159fb6529ef5/mido/backends/rtmidi.py#L51-L71) · [More projects using python-rtmidi →](https://dashboard.exa.ai/playground/search?q=python-rtmidi%20GitHub%20projects)

**Quickstart**

```python
import time
import rtmidi
midiout = rtmidi.MidiOut()
available_ports = midiout.get_ports()
if available_ports:
    midiout.open_port(0)
else:
    midiout.open_virtual_port("My virtual output")
with midiout:
    note_on = [0x90, 60, 112] # channel 1, middle C, velocity 112
    note_off = [0x80, 60, 0]
    midiout.send_message(note_on)
    time.sleep(0.5)
    midiout.send_message(note_off)
    time.sleep(0.1)
del midiout

```

From [README.md](https://api.github.com/repos/SpotlightKid/python-rtmidi/contents/README.md)

### MIDIUtil

[GitHub](https://github.com/MarkCWirt/MIDIUtil) · [PyPI](https://pypi.org/project/MIDIUtil) · [Docs](https://midiutil.readthedocs.io/en/1.2.1/)

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
- Capabilities: [From the MIDIUtil docs](https://midiutil.readthedocs.io/en/1.2.1/)

**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.

**Watch out for**

- **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.

```sh
python3 -m pip install MIDIUtil
```

**tiagoft/audio_to_midi** (113 stars)

[tiagoft/audio_to_midi](https://github.com/tiagoft/audio_to_midi) 

```python
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

```

[sound_to_midi/monophonic.py](https://github.com/tiagoft/audio_to_midi/blob/cc197d26ab4aea7e934fe53a80022bab535379a8/sound_to_midi/monophonic.py#L232-L266) · [More projects using MIDIUtil →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20MIDIUtil%20for%20live%20metronome%20scheduling%2C%20pitch-bend%20note%20conversion%20and%20generated%20music-file%20writing&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
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)

```

From [c-major-scale.py](https://github.com/MarkCWirt/MIDIUtil/blob/develop/examples/c-major-scale.py)

### Miditoolkit

[GitHub](https://github.com/YatingMusic/miditoolkit) · [PyPI](https://pypi.org/project/miditoolkit) · [Docs](https://api.github.com/repos/YatingMusic/miditoolkit/contents/README.md)

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
- Capabilities: [From the Miditoolkit docs](https://api.github.com/repos/YatingMusic/miditoolkit/contents/README.md)

**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.

**Watch out for**

- **Note timing stays in ticks.** Convert ticks before comparing note positions with audio timestamps.

```sh
python3 -m pip install miditoolkit
```

**YatingMusic/remi** (606 stars)

[YatingMusic/remi](https://github.com/YatingMusic/remi) 

```python
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)

```

[utils.py](https://github.com/YatingMusic/remi/blob/6d407258fa5828600a5474354862353ef4e4e8ae/utils.py#L216-L348) · [More projects using Miditoolkit →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20miditoolkit%20for%20live%20metronome%20scheduling%2C%20pitch-bend%20note%20conversion%20and%20generated%20music-file%20writing&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from miditoolkit import MidiFile
from miditoolkit.midi.utils import example_midi_file
path_midi = example_midi_file()
midi_obj = MidiFile(path_midi)
print(midi_obj)

```

From [README.md](https://api.github.com/repos/YatingMusic/miditoolkit/contents/README.md)

## FAQ

### Which Python MIDI library should I use?

[Mido](#mido) suits most work with MIDI messages, files, and device ports. [pretty_midi](#pretty-midi) suits analysis of notes and instruments with times in seconds. [music21](#musictwoone) suits music analysis that treats MIDI as a score.

### What is Mido?

[Mido](#mido) works with MIDI messages, MIDI files, and real-time ports through selectable backends.

### How do I read a MIDI file in Python?

[Mido](#mido) reads a MIDI file as tracks of messages with timing in ticks. [pretty_midi](#pretty-midi) reads the same file as instruments and notes with times in seconds.

### How do I create a MIDI file in Python?

[MIDIUtil](#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.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python MIDI libraries Mido pretty_midi Miditoolkit MIDIUtil code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
