This is a comprehensive request to create a MIDI music generator using Markov chains. I'll need to create a solution that:
- Analyzes existing MIDI files to learn note transition probabilities
- Builds a Markov chain from these probabilities
- Generates new melodies by walking the chain
- Outputs the result as a .mid file using mido
Let me break down what I need to include:
- A class to parse MIDI files and extract note information
- A Markov chain implementation for note transitions
- Logic to generate sequences based on the chain
- MIDI file output using mido
- Example usage and demonstration
Key considerations:
- Note representation (pitch, duration, velocity)
- Handling of rest/silence
- Building transition probabilities
- Seed selection for generation
- Output formatting
Let me create a comprehensive solution:
import os
from collections import defaultdict
from typing import List, Tuple, Dict
import random
from pathlib import Path
import mido
from mido import MidiFile, MidiTrack, Message
class MIDIMarkovChain:
"""Generate MIDI music using Markov chains"""
def __init__(self, order: int = 1):
"""
Initialize Markov chain
Args:
order: Markov chain order (1 = unigram, 2 = bigram, etc.)
"""
self.order = order
self.transitions = defaultdict(lambda: defaultdict(float))
self.note_counts = defaultdict(float)
self.all_sequences = []
def add_sequence(self, sequence: List[Tuple[int, int, int]]):
"""
Add a sequence of notes to the chain
Args:
sequence: List of (pitch, duration, velocity) tuples
"""
if len(sequence) < self.order + 1:
return
self.all_sequences.append(sequence)
for i in range(len(sequence) - self.order):
current_state = tuple(sequence[i:i + self.order])
next_note = sequence[i + self.order]
self.transitions[current_state][next_note] += 1
self.note_counts[current_state] += 1
def normalize(self):
"""Convert counts to probabilities"""
for state in self.transitions:
total = self.note_counts[state]
for note in self.transitions[state]:
self.transitions[state][note] /= total
I'm building the core Markov chain structure by storing note transitions and their frequencies. When adding sequences, I track state-to-note relationships based on the specified order, then normalize these counts into probabilities for generation.
The get_next_note method samples from the learned distribution for a given state, while generate_sequence builds new sequences by iteratively selecting notes based on the current state. If a state has no learned transitions, I fall back to a random choice from available options to keep generation flowing.
The MIDIAnalyzer class handles extracting note sequences from MIDI files by reading tracks and converting note events into tuples of pitch, duration, and velocity values. (directory: str, track_idx: int = 0) -> List[List[Tuple[int, int, int]]]:
"""
Analyze all MIDI files in directory
Args:
directory: Path to directory containing MIDI files
track_idx: Which track to extract from each file
Returns:
List of note sequences
"""
sequences = []
midi_files = list(Path(directory).glob('*.mid')) + list(Path(directory).glob('*.midi'))
print(f"Found {len(midi_files)} MIDI files")
for midi_file in midi_files:
print(f"Analyzing {midi_file.name}...")
notes = MIDIAnalyzer.extract_notes(str(midi_file), track_idx)
if notes:
sequences.append(notes)
return sequences
The method scans a directory for MIDI files, processes each one by extracting notes from a specified track, and collects all resulting sequences into a single list for return. current position. The time delta is calculated as the difference between ticks and current position, defaulting to just the ticks value if it would be negative. For each note in the sequence, a note_on message is added with the calculated time delta, followed by a note_off message after the note duration. The current time is then updated to track position in the sequence. Once all notes are processed, the MIDI file is saved to the specified output path and the filename is returned.
There's also an improved version of this method being defined that takes the same note sequence and output parameters, likely with refinements to how timing or note events are handled. ticks_per_beat: int = 480,
channel: int = 0,
quantize: bool = True
) -> str:
"""
Create MIDI file with better timing handling
Args:
note_sequence: List of (pitch, duration, velocity) tuples
output_file: Output filename
tempo: Tempo in microseconds per beat
ticks_per_beat: MIDI ticks per beat
channel: MIDI channel
quantize: Whether to quantize durations
Returns:
Path to created file
"""
mid = MidiFile(ticks_per_beat=ticks_per_beat)
track = MidiTrack()
mid.tracks.append(track)
track.append(mido.MetaMessage('set_tempo', tempo=tempo))
for pitch, duration, velocity in note_sequence:
ticks = int(duration)
if quantize:
# Quantize to nearest beat (quarter note)
ticks = round(ticks / ticks_per_beat) * ticks_per_beat
ticks = max(ticks_per_beat // 2, ticks) # Minimum duration
track.append(Message('note_on', note=pitch, velocity=velocity, time=ticks))
track.append(Message('note_off', note=pitch, velocity=0, time=ticks))
mid.save(output_file)
return output_file
Example usage and demonstration
def example_generate_from_files():
"""Example: Generate music from existing MIDI files"""
print("=" * 60)
print("MIDI Markov Chain Generator")
print("=" * 60)
# Set up a basic training MIDI with a C major scale melody
training_file = "training_sample.mid"
mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)
track.append(mido.MetaMessage('set_tempo', tempo=500000))
pitches = [60, 62, 64, 65, 67, 69, 71, 72] # C D E F G A B C
duration = 480 # Quarter note
velocity = 100
for pitch in pitches:
track.append(Message('note_on', note=pitch, velocity=velocity, time=duration))
track.append(Message('note_off', note=pitch, velocity=0, time=duration))
# Add chord progressions to enrich the training data
chords = [
[60, 64, 67], # C major
[62, 65, 69], # D minor
[64, 67, 71], # E minor
[65, 69, 72], # F major
]
for chord in chords * 2:
for pitch in chord:
track.append(Message('note_on', note=pitch, velocity=velocity, time=240))
track.append(Message('note_off', note=pitch, velocity=0, time=240))
mid.save(training_file)
print(f"\nCreated training file: {training_file}")
# Extract notes and build a first-order Markov chain
print("\nAnalyzing training MIDI file...")
notes = MIDIAnalyzer.extract_notes(training_file, track_idx=0)
print(f"Extracted {len(notes)} notes")
print(f"Sample notes: {notes[:5]}")
print("\nBuilding Markov chain (order=1)...")
chain = MIDIMarkovChain(order=1)
chain.add_sequence(notes)
chain.normalize()
print(f"Learned {len(chain.transitions)} state transitions")
# Generate and save new melody
print("\nGenerating new melody...")
generated = chain.generate_sequence(length=16)
print(f"Generated {len(generated)} notes")
print(f"Generated sequence: {generated[:10]}")
output_file = "generated_melody.mid"
MIDIGenerator.create_midi_from_sequence_improved(
generated,
output_file=output_file,
tempo=500000,
quantize=True
)
print(f"\nSaved to: {output_file}")
return output_file
def example_advanced():
"""Advanced example with multiple sequences and higher order chains"""
print("\n" + "=" * 60)
print("Advanced Example: Multi-sequence Markov Chain")
print("=" * 60)
# Create multiple training sequences
mid = MidiFile()
# Create several distinct melodic patterns
patterns = [
# Ascending scale
[60, 62, 64, 65, 67, 69, 71, 72],
# Descending scale
[72, 71, 69, 67, 65, 64, 62, 60],
# Arpeggios
[60, 64, 67, 72, 67, 64, 60]
I cannot complete this thought as the next thinking appears to be cut off mid-sentence. I need to reconsider how MIDI timing works—the time field represents delta time in ticks since the last message, not absolute timing. Let me revise the generator to handle this correctly by properly calculating tick values and quantizing note durations to maintain rhythmic integrity.
MIDI Music Generator Using Markov Chains
I'll create a comprehensive solution that analyzes MIDI files, builds Markov chains, and generates new music.
import os
from collections import defaultdict
from typing import List, Tuple, Dict, Optional
import random
from pathlib import Path
import mido
from mido import MidiFile, MidiTrack, Message, MetaMessage
class MIDIMarkovChain:
"""Generate MIDI music using Markov chains"""
def __init__(self, order: int = 1):
"""
Initialize Markov chain for MIDI notes
Args:
order: Chain order (1=unigram, 2=bigram, 3=trigram, etc.)
"""
self.order = order
self.transitions = defaultdict(lambda: defaultdict(float))
self.state_counts = defaultdict(float)
self.seed_states = []
def add_sequence(self, sequence: List[Tuple[int, int, int]]):
"""
Add a note sequence to learn from
Args:
sequence: List of (pitch, duration_ticks, velocity) tuples
"""
if len(sequence) < self.order + 1:
return
# Store first state as potential seed
self.seed_states.append(tuple(sequence[:self.order]))
# Build transitions
for i in range(len(sequence) - self.order):
current_state = tuple(sequence[i:i + self.order])
next_note = sequence[i + self.order]
self.transitions[current_state][next_note] += 1
self.state_counts[current_state] += 1
def normalize(self):
"""Convert counts to probabilities"""
for state in self.transitions:
total = self.state_counts[state]
if total > 0:
for note in self.transitions[state]:
self.transitions[state][note] /= total
def get_next_note(self, current_state: Tuple) -> Optional[Tuple[int, int, int]]:
"""Get next note based on current state using probability distribution"""
if current_state not in self.transitions:
return None
notes = list(self.transitions[current_state].keys())
probabilities = list(self.transitions[current_state].values())
return random.choices(notes, weights=probabilities, k=1)[0]
def generate_sequence(
self,
length: int,
seed: Optional[Tuple] = None,
temperature: float = 1.0
) -> List[Tuple[int, int, int]]:
"""
Generate note sequence from chain
Args:
length: Number of notes to generate
seed: Starting state (None = random)
temperature: Controls randomness (>1 = more random, <1 = more predictable)
Returns:
List of (pitch, duration, velocity) tuples
"""
if not self.transitions:
raise ValueError("No transitions learned. Add sequences first.")
# Select seed
if seed is None:
seed = random.choice(self.seed_states)
sequence = list(seed)
# Generate sequence
for _ in range(length - self.order):
current_state = tuple(sequence[-self.order:])
if current_state not in self.transitions:
# Fallback to random state
current_state = random.choice(list(self.transitions.keys()))
# Get next note with temperature
notes = list(self.transitions[current_state].keys())
probs = list(self.transitions[current_state].values())
# Apply temperature
if temperature != 1.0:
probs = [p ** (1 / temperature) for p in probs]
total = sum(probs)
probs = [p / total for p in probs]
next_note = random.choices(notes, weights=probs, k=1)[0]
sequence.append(next_note)
return sequence
def get_stats(self) -> Dict:
"""Get chain statistics"""
all_notes = []
for state in self.transitions:
for note in self.transitions[state]:
all_notes.append(note)
if not all_notes:
return {}
pitches = [note[0] for note in all_notes]
durations = [note[1] for note in all_notes]
velocities = [note[2] for note in all_notes]
return {
'num_states': len(self.transitions),
'num_unique_notes': len(set(all_notes)),
'min_pitch': min(pitches),
'max_pitch': max(pitches),
'avg_pitch': sum(pitches) / len(pitches),
'min_duration': min(durations),
'max_duration': max(durations),
'avg_duration': sum(durations) / len(durations),
'min_velocity': min(velocities),
'max_velocity': max(velocities),
'avg_velocity': sum(velocities) / len(velocities),
}
class MIDIAnalyzer:
"""Extract note sequences from MIDI files"""
@staticmethod
def extract_notes(
midi_file: str,
track_idx: int = 0,
min_velocity: int = 1
) -> List[Tuple[int, int, int]]:
"""
Extract note sequence from MIDI file
Args:
midi_file: Path to MIDI file
track_idx: Track index to extract
min_velocity: Ignore notes below this velocity
Returns:
List of (pitch, duration_ticks, velocity) tuples
"""
try:
mid = MidiFile(midi_file)
except Exception as e:
print(f"Error reading {midi_file}: {e}")
return []
if track_idx >= len(mid.tracks):
print(f"Track {track_idx} not in {midi_file}")
return []
track = mid.tracks[track_idx]
notes = []
note_events = {} # {pitch: (start_time, velocity)}
current_time = 0
# Accumulate delta times and track notes
for msg in track:
current_time += msg.time
if msg.type == 'note_on':
if msg.velocity > min_velocity:
note_events[msg.note] = (current_time, msg.velocity)
elif msg.note in note_events:
# Note on with velocity 0 = note off
del note_events[msg.note]
elif msg.type == 'note_off':
if msg.note in note_events:
start_time, velocity = note_events[msg.note]
duration = current_time - start_time
notes.append((msg.note, duration, velocity))
del note_events[msg.note]
# Handle notes that didn't have note_off
for pitch, (start_time, velocity) in note_events.items():
duration = current_time - start_time
if duration > 0:
notes.append((pitch, duration, velocity))
return notes
@staticmethod
def analyze_directory(
directory: str,
track_idx: int = 0,
max_files: Optional[int] = None
) -> List[List[Tuple[int, int, int]]]:
"""
Analyze all MIDI files in directory
Args:
directory: Path to directory
track_idx: Track to extract from each file
max_files: Limit number of files (None = all)
Returns:
List of note sequences
"""
sequences = []
midi_files = list(Path(directory).glob('*.mid')) + \
list(Path(directory).glob('*.midi'))
if max_files:
midi_files = midi_files[:max_files]
print(f"Found {len(midi_files)} MIDI files")
for midi_file in midi_files:
notes = MIDIAnalyzer.extract_notes(str(midi_file), track_idx)
if notes:
sequences.append(notes)
print(f" {midi_file.name}: {len(notes)} notes")
return sequences
@staticmethod
def print_notes(notes: List[Tuple[int, int, int]], limit: int = 10):
"""Pretty print notes"""
note_names = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
for i, (pitch, duration, velocity) in enumerate(notes[:limit]):
octave = pitch // 12
note_name = note_names[pitch % 12]
print(f" {note_name}{octave} (dur: {duration}, vel: {velocity})")
if len(notes) > limit:
print(f" ... and {len(notes) - limit} more notes")
class MIDIGenerator:
"""Generate MIDI files from note sequences"""
@staticmethod
def create_midi(
note_sequence: List[Tuple[int, int, int]],
output_file: str = "output.mid",
tempo_bpm: int = 120,
ticks_per_beat: int = 480,
quantize: bool = True,
quantize_level: int = 16, # 16th notes
min_duration: Optional[int] = None
) -> str:
"""
Create MIDI file from note sequence
Args:
note_sequence: List of (pitch, duration, velocity) tuples
output_file: Output filename
tempo_bpm: Tempo in beats per minute
ticks_per_beat: MIDI resolution
quantize: Whether to quantize note durations
quantize_level: Quantization level (16 = 16th note grid)
min_duration: Minimum note duration in ticks
Returns:
Output file path
"""
mid = MidiFile(ticks_per_beat=ticks_per_beat)
track = MidiTrack()
mid.tracks.append(track)
# Convert BPM to microseconds per beat
tempo_us = int(60_000_000 / tempo_bpm)
track.append(MetaMessage('set_tempo', tempo=tempo_us))
if min_duration is None:
min_duration = ticks_per_beat // 4 # 16th note minimum
# Add notes
time_offset = 0
for pitch, duration, velocity in note_sequence:
# Quantize duration if requested
if quantize:
quantum = ticks_per_beat // quantize_level
duration = max(quantum, round(duration / quantum) * quantum)
duration = max(min_duration, int(duration))
# Note on
track.append(Message('note_on', note=pitch, velocity=velocity, time=time_offset))
# Note off after duration
track.append(Message('note_off', note=pitch, velocity=0, time=duration))
time_offset = 0
mid.save(output_file)
print(f"Saved MIDI file: {output_file}")
return output_file
@staticmethod
def create_polyphonic_midi(
note_sequences: List[List[Tuple[int, int, int]]],
output_file: str = "output_poly.mid",
tempo_bpm: int = 120,
ticks_per_beat: int = 480
) -> str:
"""
Create MIDI with multiple simultaneous melodies
Args:
note_sequences: List of note sequences (separate lines)
output_file: Output filename
tempo_bpm: Tempo
ticks_per_beat: MIDI resolution
Returns:
Output file path
"""
mid = MidiFile(ticks_per_beat=ticks_per_beat)
tempo_us = int(60_000_000 / tempo_bpm)
for channel, note_sequence in enumerate(note_sequences):
if channel > 15: # MIDI limit
break
track = MidiTrack()
mid.tracks.append(track)
track.append(MetaMessage('set_tempo', tempo=tempo_us))
for pitch, duration, velocity in note_sequence:
duration = max(ticks_per_beat // 4, int(duration))
track.append(Message(
'note_on',
note=pitch,
velocity=velocity,
channel=channel,
time=0
))
track.append(Message(
'note_off',
note=pitch,
velocity=0,
channel=channel,
time=duration
))
mid.save(output_file)
print(f"Saved polyphonic MIDI: {output_file}")
return output_file
def example_1_simple_generation():
"""Example 1: Generate from a single training MIDI"""
print("\n" + "="*70)
print("EXAMPLE 1: Simple Generation from Synthetic Training Data")
print("="*70)
# Create training MIDI
print("\n[1] Creating training MIDI file...")
training_file = "training_melody.mid"
mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)
track.append(MetaMessage('set_tempo', tempo=500000))
# Create C major scale melody
ticks_per_beat = 480
notes = [
(60, ticks_per_beat, 100), # C
(62, ticks_per_beat, 100), # D
(64, ticks_per_beat, 100), # E
(65, ticks_per_beat, 100), # F
(67, ticks_per_beat, 100), # G
(69, ticks_per_beat, 100), # A
(71, ticks_per_beat, 100), # B
(72, ticks_per_beat, 100), # C
]
for pitch, duration, velocity in notes:
track.append(Message('note_on', note=pitch, velocity=velocity, time=duration))
track.append(Message('note_off', note=pitch, velocity=0, time=duration))
mid.save(training_file)
# Extract notes
print(f"[2] Analyzing {training_file}...")
extracted_notes = MIDIAnalyzer.extract_notes(training_file)
print(f" Extracted {len(extracted_notes)} notes:")
MIDIAnalyzer.print_notes(extracted_notes)
# Build Markov chain
print("\n[3] Building first-order Markov chain...")
chain = MIDIMarkovChain(order=1)
chain.add_sequence(extracted_notes)
chain.normalize()
stats = chain.get_stats()
print(f" States: {stats['num_states']}")
print(f" Pitch range: {stats['min_pitch']} - {stats['max_pitch']}")
print(f" Avg velocity: {stats['avg_velocity']:.0f}")
# Generate variations
print("\n[4] Generating new melodies...")
for i in range(3):
generated = chain.generate_sequence(length=16)
output_file = f"generated_variation_{i+1}.mid"
MIDIGenerator.create_midi(generated, output_file=output_file)
print(f"\n Variation {i+1}:")
MIDIAnalyzer.print_notes(generated, limit=8)
def example_2_higher_order():
"""Example 2: Higher-order Markov chains"""
print("\n" + "="*70)
print("EXAMPLE 2: Higher-Order Markov Chains")
print("="*70)
ticks = 480
# Create training data with patterns
print("\n[1] Creating training patterns...")
patterns = [
# Ascending arpeggio
[(60, ticks, 100), (64, ticks, 100), (67, ticks, 100), (72, ticks, 100)],
# Descending
[(72, ticks, 100), (67, ticks, 100), (64, ticks, 100), (60, ticks, 100)],
# Repeated notes
[(65, ticks//2, 100), (65, ticks//2, 100), (67, ticks, 100), (69, ticks, 100)],
# Triplet pattern
[(60, ticks, 100), (62, ticks, 100), (64, ticks, 100),
(62, ticks, 100), (64, ticks, 100), (65, ticks, 100)],
]
# Build chains of different orders
for order in [1, 2]:
print(f"\n[2] Building order-{order} Markov chain...")
chain = MIDIMarkovChain(order=order)
for pattern in patterns:
chain.add_sequence(pattern)
chain.normalize()
print(f" States: {len(chain.transitions)}")
# Generate
print(f"[3] Generating with order-{order}...")
for i in range(2):
generated = chain.generate_sequence(length=20, temperature=0.8)
output_file = f"generated_order{order}_var{i+1}.mid"
MIDIGenerator.create_midi(generated, output_file=output_file)
if i == 0:
print(f" Generated sequence:")
MIDIAnalyzer.print_notes(generated, limit=10)
def example_3_multiple_files():
"""Example 3: Train from multiple MIDI files"""
print("\n" + "="*70)
print("EXAMPLE 3: Training from Multiple Files")
print("="*70)
# Create sample directory
sample_dir = "midi_samples"
os.makedirs(sample_dir, exist_ok=True)
print(f"\n[1] Creating {sample_dir}/...")
# Create different melodic styles
styles = [
{
'name': 'scale',
'pitches': [60, 62, 64, 65, 67, 69, 71, 72, 71, 69, 67, 65, 64, 62, 60]
},
{
'name': 'arpeggios',
'pitches': [60, 64, 67, 72] * 4
},
{
'name': 'pentatonic',
'pitches': [60, 62, 65, 67, 70] * 3
}
]
for style in styles:
mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)
track.append(MetaMessage('set_tempo', tempo=500000))
for pitch in style['pitches']:
track.append(Message('note_on', note=pitch, velocity=100, time=480))
track.append(Message('note_off', note=pitch, velocity=0, time=480))
filename = f"{sample_dir}/melody_{style['name']}.mid"
mid.save(filename)
print(f" Created {filename}")
# Analyze directory
print(f"\n[2] Analyzing directory...")
sequences = MIDIAnalyzer.analyze_directory(sample_dir)
# Combine into one chain
print(f"\n[3] Building combined Markov chain...")
chain = MIDIMarkovChain(order=2)
for seq in sequences:
chain.add_sequence(seq)
chain.normalize()
print(f" States: {len(chain.transitions)}")
# Generate fusion
print(f"\n[4] Generating fusion melody...")
generated = chain.generate_sequence(length=32, temperature=1.2)
output_file = "generated_fusion.mid"
MIDIGenerator.create_midi(generated, output_file=output_file, tempo_bpm=100)
print(f" Generated sequence:")
MIDIAnalyzer.print_notes(generated, limit=15)
def example_4_temperature_control():
"""Example 4: Temperature control for randomness"""
print("\n" + "="*70)
print("EXAMPLE 4: Temperature Control")
print("="*70)
ticks = 480
training = [
(60, ticks, 100), (62, ticks, 100), (64, ticks, 100), (65, ticks, 100),
(67, ticks, 100), (69, ticks, 100), (71, ticks, 100), (72, ticks, 100),
] * 3
print("\n[1] Building chain...")
chain = MIDIMarkovChain(order=1)
chain.add_sequence(training)
chain.normalize()
print("[2] Generating with different temperatures...")
temperatures = [0.5, 1.0, 1.5]
labels = ["Conservative", "Normal", "Random"]
for temp, label in zip(temperatures, labels):
print(f"\n Temperature {temp} ({label}):")
generated = chain.generate_sequence(length=20, temperature=temp)
output_file = f"generated_temp_{temp}.mid"
MIDIGenerator.create_midi(generated, output_file=output_file)
MIDIAnalyzer.print_notes(generated, limit=10)
def example_5_statistics():
"""Example 5: Analyze and display statistics"""
print("\n" + "="*70)
print("EXAMPLE 5: Chain Statistics")
print("="*70)
# Create varied training data
ticks = 480
training_sequences = [
[(60 + i, ticks, 80 + i*5) for i in range(8)],
[(72 - i, ticks // 2, 100 + i*3) for i in range(12)],
[(60 + i*2, ticks, 90) for i in range(6)],
]
print("\n[1] Building chain...")
chain = MIDIMarkovChain(order=1)
for seq in training_sequences:
chain.add_sequence(seq)
chain.normalize()
# Display statistics
stats = chain.get_stats()
print("\n[2] Chain Statistics:")
print(f" Number of states: {stats['num_states']}")
print(f" Unique notes: {stats['num_unique_notes']}")
print(f" \nPitch Statistics:")
print(f" Min: {stats['min_pitch']} (MIDI note)")
print(f" Max: {stats['max_pitch']}")
print(f" Average: {stats['avg_pitch']:.1f}")
print(f" \nDuration Statistics (ticks):")
print(f" Min: {stats['min_duration']}")
print(f" Max: {stats['max_duration']}")
print(f" Average: {stats['avg_duration']:.1f}")
print(f" \nVelocity Statistics:")
print(f" Min: {stats['min_velocity']}")
print(f" Max: {stats['max_velocity']}")
print(f" Average: {stats['avg_velocity']:.1f}")
if __name__ == "__main__":
# Run all examples
example_1_simple_generation()
example_2_higher_order()
example_3_multiple_files()
example_4_temperature_control()
example_5_statistics()
print("\n" + "="*70)
print("All examples completed! Check generated .mid files.")
print("="*70)
Installation
pip install mido python-rtmidi
Complete Usage Guide
# 1. BASIC USAGE - Generate from a single MIDI file
analyzer = MIDIAnalyzer()
notes = analyzer.extract_notes("your_song.mid")
chain = MIDIMarkovChain(order=2)
chain.add_sequence(notes)
chain.normalize()
generated = chain.generate_sequence(length=32)
MIDIGenerator.create_midi(generated, "output.mid")
# 2. TRAIN FROM MULTIPLE FILES
sequences = analyzer.analyze_directory("midi_folder/")
chain = MIDIMarkovChain(order=2)
for seq in sequences:
chain.add_sequence(seq)
chain.normalize()
generated = chain.generate_sequence(length=48)
MIDIGenerator.create_midi(generated, "generated.mid", tempo_bpm=120)
# 3. CONTROL RANDOMNESS WITH TEMPERATURE
# Temperature < 1.0 = more predictable
generated_conservative = chain.generate_sequence(length=32, temperature=0.5)
# Temperature > 1.0 = more random
generated_random = chain.generate_sequence(length=32, temperature=1.5)
# 4. GET STATISTICS
stats = chain.get_stats()
print(f"Pitch range: {stats['min_pitch']} to {stats['max_pitch']}")
print(f"Average velocity: {stats['avg_velocity']}")
Key Features
✅ Markov Chain Orders: Supports 1st, 2nd, 3rd order and higher
✅ Temperature Control: Adjust randomness of generation
✅ Multiple Training Sources: Combine multiple MIDI files
✅ Statistics: Analyze learned patterns
✅ Quantization: Optional note duration quantization
✅ MIDI Format: Direct .mid file output
Run all examples:
python midi_markov.py
This will generate 15+ new MIDI files demonstrating different aspects of the Markov chain music generator!