Skip to content

Instantly share code, notes, and snippets.

@ThePyceIsRight
Created March 11, 2023 20:09
Show Gist options
  • Save ThePyceIsRight/ae5f9443efb96b71402cf94a4ee7aba9 to your computer and use it in GitHub Desktop.
Save ThePyceIsRight/ae5f9443efb96b71402cf94a4ee7aba9 to your computer and use it in GitHub Desktop.
import mido
# Create a new MIDI file with one track
mid = mido.MidiFile()
track = mido.MidiTrack()
mid.tracks.append(track)
# Set the tempo (in microseconds per quarter note)
tempo = mido.bpm2tempo(120)
track.append(mido.MetaMessage('set_tempo', tempo=tempo))
# Define the note-to-MIDI pitch mapping
pitch_map = {'C': 60, 'C#': 61, 'D': 62, 'D#': 63,
'E': 64, 'F': 65, 'F#': 66, 'G': 67,
'G#': 68, 'A': 69, 'A#': 70, 'B': 71}
# Define the note durations (in ticks)
quarter_note = mido.tick2second(1, mid.ticks_per_beat, tempo) * 4
durations = {'1': quarter_note, '2': quarter_note / 2, '4': quarter_note / 4,
'8': quarter_note / 8, '16': quarter_note / 16}
# Notes and beats in your notation
notes = ['G-4-4', 'G-4-4', 'G-4-4', 'D#-4-8', 'B-3-8', 'A#-3-4', 'G-4-4', 'D#-4-8', 'B-3-8', 'A#-3-4', 'G-4-4', 'D#-4-8', 'B-3-8', 'C-4-2', 'G-4-4', 'G-4-4', 'G-4-4', 'D#-4-8', 'B-3-8', 'A#-3-4', 'G-4-4', 'D#-4-8', 'B-3-8', 'A#-3-4', 'G-4-4', 'D#-4-8', 'B-3-8', 'C-4-2', 'G-4-4', 'G-4-4', 'G-4-4', 'D#-4-8', 'B-3-8', 'A#-3-4', 'G-4-4', 'D#-4-8', 'B-3-8', 'A#-3-4', 'G-4-4', 'D#-4-8', 'B-3-8', 'C-4-2', 'G-4-4', 'G-4-4', 'G-4-4', 'D#-4-8', 'B-3-8', 'A#-3-4', 'G-4-4', 'D#-4-8', 'B-3-8', 'A#-3-4', 'G-4-4', 'D#-4-8', 'B-3-8', 'C-4-2']
# Convert the notes and beats into MIDI messages
time = 0
for note in notes:
note_parts = note.split('-')
pitch = pitch_map[note_parts[0]]
duration = durations[note_parts[1]]
track.append(mido.Message('note_on', note=pitch, velocity=127, time=time))
time
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment