💾 Archived View for thrig.me › blog › 2023 › 10 › 07 › rain.pl captured on 2023-11-14 at 09:03:33.

View Raw

More Information

⬅️ Previous capture (2023-11-04)

-=-=-=-=-=-=-

#!/usr/bin/env perl
# rain - cowbell + white(ish) noise == rain?
use 5.26.0;
use warnings;
use MIDI;
sub COWBELL () { 56 }
sub DRUMS ()   { 9 }
sub MAXTIME () { 10240 }
sub NOW ()     { 0 }
sub QUIET ()   { 0 }

my $file = shift // 'rain.midi';

my $track_count = 16;

# probably rain should be quiet background noise, this is up pretty high
# so I can hear it better over background noise
sub velo { 90 + int rand 15 }

sub makeatrack {
    state $pan = 48;    # NOTE depends on track_count
    my @events;
    my ( $epoch, $notedur, $rand ) = ( 0, 12, rand 4096 );
    while (1) {
        my $delay = 20 + int rand $rand;
        $epoch += $delay + $notedur;
        last if $epoch >= MAXTIME;
        push @events,
          [ control_change => $delay, DRUMS, 0x0A, $pan ],
          [ note_on        => NOW, DRUMS, COWBELL, velo ],
          [ note_off       => $notedur, DRUMS, COWBELL, QUIET ];
        $rand -= int rand 1024;
        $rand = 512 if $rand < 512;
    }
    $pan += 2;    # NOTE depends on track_count
    MIDI::Track->new( { events => \@events } );
}

sub gentracks { [ map makeatrack, 1 .. $track_count ] }

MIDI::Opus->new( { tracks => gentracks } )->write_to_file($file);