Created
February 21, 2023 15:16
-
-
Save yolisses/d0fd9eb590e6edf21072845155d782ae to your computer and use it in GitHub Desktop.
Plot MIDI in Python with pretty_midi and pyplot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pretty_midi as pm | |
from itertools import cycle | |
import matplotlib.pyplot as plt | |
import matplotlib.patches as patches | |
def plot_midi(midi: pm.PrettyMIDI): | |
fig, ax = plt.subplots() | |
colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] | |
colors = cycle(colors) | |
for instrument in midi.instruments: | |
color = next(colors) | |
for note in instrument.notes: | |
rectangle = patches.Rectangle( | |
[note.start, note.pitch], | |
note.end - note.start, 1, | |
facecolor=color | |
) | |
ax.add_patch(rectangle) | |
rectangle = patches.Rectangle( | |
[note.start, note.pitch], | |
0.05, 1, | |
facecolor='#0004', | |
) | |
ax.add_patch(rectangle) | |
ax.plot() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment