I'm focused on grasping the essence of the task: crafting a Python program for MIDI music generation. It's about random creation, and the output format is crucial. I'm already envisioning the need for specific libraries to streamline MIDI file handling.
Refining the Framework
I'm presently building out the program's skeleton. I've begun to select midiutil as the core MIDI library and am establishing the fundamental musical elements like pitch, duration, and velocity. I'm focusing on defining a basic note selection process, and the potential inclusion of tempo variation.
Defining Musical Structures
I'm now zeroing in on musical theory to guide the randomness. My goal is to incorporate a function to construct a scale based on a user-provided root note, thus enabling the creation of music in various keys. This will avoid the issues of random notes sounding dissonant. I'm prioritizing the C major scale, for simplicity, and then will add note durations.
Codifying Musical Ideas
I'm translating the musical concept into Python. I've initiated the program structure, installing midiutil and including import statements. I've started establishing essential parameters such as track, channel, time, and tempo. My next steps involve incorporating the scale logic to generate a key for musical generation and then implement rhythmic considerations.
Formulating Code Structure
I'm now integrating the musical logic into a functional Python script. I have established the core structure, including a scale generator to promote musicality. The core rhythm logic is in place, using weighted probabilities to provide variance. I will also incorporate explanatory comments for understanding. Finally, I will explain output format considerations.
Synthesizing the Solution
I'm now integrating all these thoughts into a comprehensive structure. I've designed a clear scale generator, incorporating weighted rhythm probabilities to enhance the musicality of the output. I'm focusing on providing informative comments and detailed explanations to facilitate user comprehension. The final aspect will be discussing output and file playback.
To generate MIDI files in Python, the easiest library to use is midiutil. It handles the complex byte-writing part of the MIDI standard, allowing you to focus on the musical logic (notes, timing, and volume).
Prerequisites
You will need to install the midiutil library first:
bash
pip install midiutil
Python Program
Here is a script that generates a random melody. To make it sound "musical" rather than just random noise, I have restricted the random choices to a specific Key (C Major) and defined specific Rhythms.
python
import random
from midiutil import MIDIFile
def generate_random_midi(filename="output.mid", num_notes=60, tempo=120):
# 1. create the MIDIFile object with 1 track
track = 0
channel = 0
time = 0 # In beats
volume = 100 # 0-127, as per MIDI standard
MyMIDI = MIDIFile(1) # One track
# Add track name and tempo
MyMIDI.addTrackName(track, time, "Random Python Track")
MyMIDI.addTempo(track, time, tempo)
# 2. Define Musical Constants
# MIDI Note numbers: 60 is Middle C
# A simple Major scale pattern (Tone, Tone, Semitone, Tone, Tone, Tone, Semitone)
major_scale_intervals = [0, 2, 4, 5, 7, 9, 11]
root_note = 60 # C4
# Build a pool of allowed notes (across 3 octaves)
allowed_pitches = []
for octave in range(0, 3):
for interval in major_scale_intervals:
# Calculate exact MIDI note number
note = root_note + (octave * 12) + interval
allowed_pitches.append(note)
# Define allowed durations (in beats)
# 0.25 = 16th note, 0.5 = 8th, 1 = Quarter, 2 = Half, 4 = Whole
# We repeat common values to make them statistically more likely
allowed_durations = [0.25, 0.5, 0.5, 0.5, 1, 1, 1, 1, 2]
# 3. Generate the Notes
for i in range(num_notes):
pitch = random.choice(allowed_pitches)
duration = random.choice(allowed_durations)
# Add a bit of randomness to volume (humanize)
current_volume = random.randint(80, 120)
# Add the note to the MIDI file
# arguments: track, channel, pitch, time (start), duration, volume
MyMIDI.addNote(track, channel, pitch, time, duration, current_volume)
# Advance the time cursor so the next note plays after this one
# Occasionally add a rest (silence) by advancing time more than the note duration
if random.random() < 0.1: # 10% chance of a rest
time += duration + random.choice([0.5, 1])
else:
time += duration
# 4. Save the file
with open(filename, "wb") as output_file:
MyMIDI.writeFile(output_file)
print(f"Generated '{filename}' with {num_notes} notes.")
if __name__ == "__main__":
generate_random_midi("random_music.mid", num_notes=100, tempo=130)
How it works:
The Library: Uses midiutil.MIDIFile to manage the file structure.
Musical Theory:
Raw random numbers (e.g., 0 to 127) sound dissonant and messy.
The script builds a list called allowed_pitches based on the C Major Scale. This ensures that no matter which note is picked, it will sound "in key."
Timing:
The time variable acts as a cursor.
After a note is added, time is incremented by the duration. If we didn't do this, all 100 notes would play instantly at the exact same time (one giant chord).
Output: It writes a binary file (.mid) to your disk.
How to listen to the result:
MIDI files do not contain sound waves; they contain data (instructions). To hear it, you need to open the resulting .mid file in:
Windows Media Player / VLC
GarageBand / Logic Pro
MuseScore
Online MIDI player (e.g., onlinesequencer.net)
Customization Ideas:
Change the scale: Change major_scale_intervals to [0, 3, 5, 6, 7, 10] to generate a Blues scale.
Chords: Instead of adding one note per loop, add 3 notes at the same time value to create a chord.
Silence: The code currently has a 10% chance to add a "rest" (silence) to make the phrasing sound more natural. Increase 0.1 to make the song sparser.