Providing Markov chain MIDI generation code
Here's example Python code using mido that learns note transitions from existing MIDI files, builds a Markov chain, generates a new melody by random walk, and saves it as a new MIDI file.
Below is a simple Python example that:
- Loads one or more MIDI files and extracts a sequence of note-on pitches (ignoring velocity and duration).
- Builds a first-order Markov chain of note transitions.
- Generates a new melody by randomly walking the Markov chain.
- Saves the result as a
.mid file using mido.
You can adapt it for more advanced timing, velocities, channels, etc.
import os
import random
from mido import MidiFile, MidiTrack, Message
def extract_notes_from_midi(path):
"""Return a list of note numbers from 'note_on' messages with velocity > 0."""
mid = MidiFile(path)
notes = []
for track in mid.tracks:
for msg in track:
if msg.type == 'note_on' and msg.velocity > 0:
notes.append(msg.note)
return notes
def build_transition_model(midi_files):
"""Build a Markov transition dictionary from a collection of MIDI files."""
transitions = {}
counts = {}
for mf in midi_files:
note_sequence = extract_notes_from_midi(mf)
# Build pairwise transitions
for i in range(len(note_sequence) - 1):
curr_note = note_sequence[i]
next_note = note_sequence[i + 1]
if curr_note not in counts:
counts[curr_note] = {}
counts[curr_note][next_note] = counts[curr_note].get(next_note, 0) + 1
# Convert counts to probability lists
for curr_note, nexts in counts.items():
total = sum(nexts.values())
transitions[curr_note] = []
weights = []
for nt, ct in nexts.items():
transitions[curr_note].append(nt)
weights.append(ct / total)
# Store as (next_note_list, weight_list)
counts[curr_note] = (transitions[curr_note], weights)
return counts # keys: curr_note -> (list_of_next_notes, list_of_probabilities)
def generate_melody(model, length=50):
"""Generate a melody of given length using the Markov model."""
if not model:
return []
# Pick a random starting note
start_note = random.choice(list(model.keys()))
melody = [start_note]
for _ in range(length - 1):
curr_note = melody[-1]
if curr_note not in model:
# If no outgoing edges, pick a new random note from the model
curr_note = random.choice(list(model.keys()))
next_notes, probs = model[curr_note]
# Randomly choose next note by probabilities
melody.append(random.choices(next_notes, probs)[0])
return melody
def save_melody_to_midi(melody, output_path, ticks_per_beat=480, note_length=240, velocity=64):
"""Save a melody (list of MIDI note numbers) to a MIDI file."""
mid = MidiFile(ticks_per_beat=ticks_per_beat)
track = MidiTrack()
mid.tracks.append(track)
time = 0
for note in melody:
# Note on
track.append(Message('note_on', note=note, velocity=velocity, time=time))
# Note off after note_length ticks
track.append(Message('note_off', note=note, velocity=velocity, time=note_length))
time = 0 # subsequent events have time=0; note_length is used above
mid.save(output_path)
print(f"Saved generated melody to {output_path}")
if __name__ == "__main__":
# Point this to a folder with your MIDI files or a list of file paths
midi_folder = "path/to/your/midi/files"
midi_files = [
os.path.join(midi_folder, f)
for f in os.listdir(midi_folder)
if f.lower().endswith(".mid")
]
model = build_transition_model(midi_files)
new_melody = generate_melody(model, length=64) # adjust length as desired
save_melody_to_midi(new_melody, "generated_markov.mid")
How it works:
- Extract note events from each MIDI file to get an ordered list of pitches.
- Build transition probabilities: for each note, count how often each next note follows; convert counts to probabilities.
- Generate a new sequence by starting from a random note in the model and repeatedly sampling the next note based on the learned probabilities.
- Save the sequence to a new
.mid file.
You can adjust the number of generated notes, note lengths, velocities, or make the chain higher-order (e.g., using pairs of notes as states) for more complex behavior.