After having helped out primus with Win32::MIDI and seeing LostS's songs, I decided to try my hand at a very basic Win32::MIDI player. It can read a song from a comma seperated values file or you can hard code the song in. I didn't use Text::CSV since this is really just a play thing but I might rewrite it later to do so.
Before I show you the code, let me explain the format of the CSV files. Each line should have NOTE,DURATION,OCTAVE,ON/OFF as understood by Win32::MIDI.
I have added support for a rest. NOTE is R. OCTAVE and ON/OFF are ignored.
mary.txt
E,0.5,3,1 D,0.25,3,1 C,0.5,3,1 D,0.5,3,1 E,0.5,3,1 E,0.5,3,1 E,0.75,3,1 D,0.5,3,1 D,0.5,3,1 D,0.5,3,1 E,0.5,3,1 G,0.5,3,1 G,0.5,3,1
AC/DC - A Whole Lot of Rosie
song.txt
D,0.25,3,1 F,0.25,3,1 D,0.25,3,1 G,0.25,3,1 D,0.25,3,1 F,0.25,3,1 D,0.25,3,1 R,2,1,1 D,0.25,3,1 F,0.25,3,1 D,0.25,3,1 G,0.25,3,1 D,0.25,3,1 F,0.25,3,1 D,0.25,3,1 R,2,1,1 D,0.25,3,1 F,0.25,3,1 D,0.25,3,1 G,0.25,3,1 D,0.25,3,1 F,0.25,3,1 D,0.25,3,1
And now for the code!
#!/perl/bin/perl -w use strict; use Win32::MIDI; my $midi_obj = Win32::MIDI->new(); $midi_obj->openDevice(0); if (scalar @ARGV == 0) { play_file("mary.txt"); play_file("song.txt"); melody(day_tripper(3)); } else { for my $song (@ARGV) { play_file($song); } } sleep(1); $midi_obj->closeDevice(); exit(0); sub note { # note(NOTE, DURATION, OCTAVE, ON/OFF); my ($note, $duration, $octave, $on) = @_; # play_note(NOTE, DURATION, VELOCITY, CHANNEL, ON/OFF, OCTAVE) if ($note ne 'R') { $midi_obj->play_note($note, $duration, 127, 1, $on, $octave) || print $midi_obj->error() . "\n" and $midi_obj->reset_error(); } else { select(undef, undef, undef, $duration); # Rest for this $duration } } sub melody { # ([NOTE, DURATION, OCTAVE, ON/OFF], [NOTE, DURATION, OCTAVE, ON/OFF +],...) for my $melody (@_) { note(@$melody); } sleep(3); } sub play_file { my $file = shift; my @song; open(MID, "<", $file); for my $line (<MID>) { my ($note, $duration, $octave, $on) = split/,/, $line; push @song, [split /,/, $line]; } close(MID); melody(@song); } sub day_tripper { # 'Day Tripper' by the Beatles my $octave = shift; my @song; for (0..2) { push @song, ( ['E', 1.25, $octave, 1], ['G', 0.5, $octave, 1], ['G#', 0.25, $octave, 1], ['B', 0.25, $octave, 1], ['E', 0.25, $octave, 1], ['D', 0.25, $octave, 1], ['D', 1, $octave, 1], ['B', 0.25, $octave, 1], ['F#', 0.25, $octave, 1], ['F', 0.25, $octave, 1], ['B', 0.25, $octave, 1], ['D', 0.25, $octave, 1], ['E', 0.25, $octave, 1], ); } return @song; }
Update: all music was "transcribed" by LostS.
Update 2: Plays all song files listed on the command line or enters "demo" mode if you do not specify any files.
In reply to Win32::MIDI Player by Mr. Muskrat
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |