I thought that it would be cool to randomly create a MIDI file.
#!/usr/bin/perl -w use strict; use MIDI; my %chords = ( major => [0, 4, 7, 12], minor => [0, 3, 7, 12], major7 => [0, 4, 7, 11], minor7 => [0, 3, 7, 10], minor75 => [0, 3, 6, 10], dim => [0, 3, 6, 9], dom7 => [0, 4, 7, 10], major9 => [0, 4, 7, 11, 14], minor9 => [0, 3, 7, 10, 14], ); my @chords = keys %chords; # chord names my @notes = qw( C Cs D Ds E F Fs G Gs A As B ); # note names my $chord = $chords[int(rand 9)]; my $octave = int(rand 6) + 2; my $key = $notes[int(rand 12)]; my $num_tracks = int(rand 3) + 2; my @track; for my $track (0..$num_tracks) { $track[$track] = MIDI::Track->new; if ($track == 0) { $track[0]->events( ['text_event', 0, 'Random MIDI Music'] ); next; } my $notes = int(rand 10) + 10; my $volume = int(rand 63) + 64; my $patch = int(rand 127) + 1; # instrument #my $channel = int(rand 15) + 1; # now using the track number as th +e channel my $loc = 0; $track[$track]->new_event('patch_change', 0, $track, $patch); for (1 .. $notes) { my $dur = int(rand 300) + 1; my $decide = int(rand 2); my $note = $MIDI::note2number{$key.$octave}; $note = $decide ? $note : int(rand $note + 16) - 8; # randomizatio +n :) rand_notes($track, $loc, $dur, $track, $note, $volume, $chords{$ch +ord}); $loc += $dur; } } my $tracks = \@track; my $opus = MIDI::Opus->new( { 'format' => 1, 'ticks' => 96, 'tracks' => [ @$tracks ] } ); $opus->write_to_file('random.mid'); sub chord { # chord(ROOT, CHORD) # ROOT is the base note of the chord # CHORD is a reference to the chord array my ($root, $chord) = @_; my @chord = @$chord; return map { $_ += $root; } @chord; } sub rand_notes { # rand_notes(TRACK, START, DURATION, CHANNEL, ROOT, VOLUME, CHORD) my ($track, $start, $dur, $chan, $root, $vol, $chord) = @_; my @chord = chord($root, $chord); my $notes = @chord; my $rand_notes = int(rand $notes) + 1; my @rand; for (1..$rand_notes) { my $note = int(rand $notes); push(@rand, $chord[$note]); $track[$track]->new_event('note_on', $start, $chan, $chord[$note], + $vol); } for my $note (@rand) { $track[$track]->new_event('note_off', $start+ +$dur, $chan, $note, $vol); } }
Updated. Thanks again belg4mit.
Update2:Linux users, would you please try this and see if it works for you? The problem was format => 0. Changing it to 1 solved the problem. Thank you zentara!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Create MIDI With Random Tracks
by belg4mit (Prior) on Feb 17, 2003 at 23:39 UTC | |
by Mr. Muskrat (Canon) on Feb 18, 2003 at 13:39 UTC | |
|
Re: Create MIDI With Random Tracks
by zentara (Cardinal) on Feb 18, 2003 at 15:45 UTC | |
by Mr. Muskrat (Canon) on Feb 18, 2003 at 15:48 UTC | |
by zentara (Cardinal) on Feb 18, 2003 at 15:59 UTC | |
by Mr. Muskrat (Canon) on Feb 18, 2003 at 16:24 UTC | |
|
Re: Create MIDI With Random Tracks
by webratta (Sexton) on Mar 05, 2003 at 16:59 UTC |