import mido
from mido import MidiFile, MidiTrack, Message, MetaMessage
import random
# Create a new MIDI file with default ticks_per_beat=480
mid = MidiFile(ticks_per_beat=480)
# Create a single track for the melody
track = MidiTrack()
mid.tracks.append(track)
# Set the tempo to 120 BPM (500000 microseconds per beat)
track.append(MetaMessage('set_tempo', tempo=500000, time=0))
# Set instrument to Acoustic Grand Piano (program 0) on channel 0
track.append(Message('program_change', program=0, channel=0, time=0))
# C Major scale notes (MIDI note numbers, C4=60 to C6=72)
scale = [60, 62, 64, 65, 67, 69, 71, 72, 74, 76, 77, 79, 81, 83]
# Possible durations in ticks: eighth(120), quarter(240), dotted quarter(360), half(480)
durations = [120, 240, 360, 480]
# Possible velocities (volume): soft to loud
velocities = [40, 60, 80, 100, 120]
# Generate 200 random notes for a ~2-3 minute piece (depending on durations)
num_notes = 200
for i in range(num_notes):
# Choose random note from scale, pitch, duration, velocity
pitch = random.choice(scale)
duration = random.choice(durations)
velocity = random.choice(velocities)
# Optional short rest before note (0, 60, or 120 ticks)
rest = random.choice([0, 60, 120])
# Add note_on event (delta time = rest)
track.append(Message('note_on', note=pitch, velocity=velocity, time=rest, channel=0))
# Add note_off event (delta time = duration)
track.append(Message('note_off', note=pitch, velocity=0, time=duration, channel=0))
# End of track (with some padding time)
track.append(MetaMessage('end_of_track', time=1000))
# Save the MIDI file
filename = 'random_music.mid'
mid.save(filename)
print(f"Generated random music saved as '{filename}'")
# Optional: Print some info about the file
print(f"MIDI file info:")
print(f" - Ticks per beat: {mid.ticks_per_beat}")
print(f" - Number of tracks: {len(mid.tracks)}")
print(f" - Length: {mid.length} seconds (approx.)")
print("\nTo play:")
print(" - Use VLC, Windows Media Player, or any MIDI player.")
print(" - Online: Upload to https://onlinesequencer.net/ or similar.")
print(" - Command line: timidity random_music.mid (if installed)")
Installation and Usage
- Install the required library:
pip install mido
- Run the script:
python generate_random_music.py
- A file
random_music.mid will be created. It's a simple random melody in C major scale on piano, with varying rhythm, volume, and short rests. Each run generates a unique piece!
This keeps it musical (scale-based) yet random. For more complexity, you could add chords, multiple tracks, or drums—let me know if you'd like extensions! 🎹