Created
May 6, 2014 23:45
-
-
Save bentglasstube/aa21b70ec7750c3a4188 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use 5.010; | |
use strict; | |
use warnings; | |
use MIDI::Simple; | |
our $notes_per_phrase = 8; | |
our $rest_chance = 0.25; | |
our @notes = qw(A4 B4 C D E); | |
sub generate_rhythm { | |
# TODO music theory | |
return [ map { rand() < $rest_chance ? 0 : 1 } 1 .. $notes_per_phrase - 1 ]; | |
} | |
sub generate_phrase { | |
my $rhythm = generate_rhythm; | |
return [ $notes[0], map { $_ ? $notes[ int @notes * rand ] : 'rest' } @$rhythm ]; | |
} | |
sub generate_from_pattern { | |
my ($patterns, $generator) = @_; | |
my $i = int(rand() * @$patterns); | |
my $p = $patterns->[$i]; | |
my %subs = (); | |
my @result = (); | |
foreach (split //, $p) { | |
$subs{$_} ||= $generator->(); | |
push @result, @{ $subs{$_} }; | |
} | |
return \@result; | |
} | |
sub midify { | |
my ($notes) = @_; | |
new_score; | |
set_tempo 250_000; | |
noop 'c1', 'f', 'o5'; | |
n 'qn', $_ for @$notes; | |
write_score 'sample.mid'; | |
} | |
my $patterns = [qw[aaba abab abcb aabb abac abca]]; | |
my $melody = generate_from_pattern $patterns, sub { | |
generate_from_pattern $patterns, sub { | |
generate_from_pattern $patterns, sub { | |
generate_phrase; | |
} | |
} | |
}; | |
midify $melody; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment