home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / MIDI.pm < prev    next >
Encoding:
Perl POD Document  |  2002-11-16  |  16.2 KB  |  427 lines

  1.  
  2. # Time-stamp: "2002-11-16 02:11:47 MST"
  3. require 5;
  4. package MIDI;
  5. use strict;
  6. use vars qw($Debug $VERSION %number2note %note2number %number2patch
  7.         %patch2number %notenum2percussion %percussion2notenum);
  8. use MIDI::Opus;
  9. use MIDI::Track;
  10. use MIDI::Event;
  11. use MIDI::Score;
  12. # Doesn't use MIDI::Simple -- but MIDI::Simple uses this
  13.  
  14. $Debug = 0; # currently doesn't do anything
  15. $VERSION = 0.80;
  16.  
  17. # MIDI.pm doesn't do much other than 1) 'use' all the necessary submodules
  18. # 2) provide some publicly useful hashes, 3) house a few private routines
  19. # common to the MIDI::* modules, and 4) contain POD, glorious POD.
  20.  
  21. =head1 NAME
  22.  
  23. MIDI - read, compose, modify, and write MIDI files
  24.  
  25. =head1 SYNOPSIS
  26.  
  27.  use MIDI;
  28.  $chimes_track = MIDI::Track->new({ 'events' => [
  29.   ['text_event',0, 'www.ely.anglican.org/parishes/camgsm/chimes.html'],
  30.   ['text_event',0, 'Lord through this hour/ be Thou our guide'],
  31.   ['text_event',0, 'so, by Thy power/ no foot shall slide'],
  32.   ['text_event',0, '(coded at ' . scalar(localtime) . ' )'],
  33.   ['patch_change', 0, 1, 8], # Patch 8 = Celesta
  34.   map( (['note_on',0,1,$_->[0],96], ['note_off',$_->[1],1,$_->[0],0]),
  35.        [25,96],[29,96],[27,96],[20,192],[25,96],[27,96],[29,96],[25,192],
  36.        [29,96],[25,96],[27,96],[20,192],[20,96],[27,96],[29,96],[25,192],
  37.      )# [Note,Duration] ==> ['note_on',0,1, N ,96], ['note_off', D ,1, N ,0]
  38.  ] });
  39.  $chimes = MIDI::Opus->new(
  40.   { 'format' => 0, 'ticks' => 96, 'tracks' => [ $chimes_track ] } );
  41.  $chimes->write_to_file('chimes.mid');
  42.  
  43. =head1 DESCRIPTION
  44.  
  45. This suite of modules provides routines for reading, composing, modifying,
  46. and writing MIDI files.
  47.  
  48. From FOLDOC (C<http://wombat.doc.ic.ac.uk/foldoc/>):
  49.  
  50. =over
  51.  
  52. B<MIDI, Musical Instrument Digital Interface>
  53.                                        
  54. E<lt>multimedia, file formatE<gt> (MIDI /mi'-dee/, /mee'-dee/) A
  55. hardware specification and protocol used to communicate note and
  56. effect information between synthesisers, computers, music keyboards,
  57. controllers and other electronic music devices. [...]
  58.  
  59. The basic unit of information is a "note on/off" event which includes
  60. a note number (pitch) and key velocity (loudness). There are many
  61. other message types for events such as pitch bend, patch changes and
  62. synthesizer-specific events for loading new patches etc.
  63.  
  64. There is a file format for expressing MIDI data which is like a dump
  65. of data sent over a MIDI port. [...]
  66.  
  67. =back
  68.  
  69. =head1 COMPONENTS
  70.  
  71. The MIDI-Perl suite consists of these modules:
  72.  
  73. L<MIDI> (which you're looking at), L<MIDI::Opus>, L<MIDI::Track>, 
  74. L<MIDI::Event>, L<MIDI::Score>, and
  75. L<MIDI::Simple>.  All of these contain documentation in pod format.
  76. You should read all of these pods.
  77.  
  78. The order you want to read them in will depend on what you want to do
  79. with this suite of modules: if you are focused on manipulating the
  80. guts of existing MIDI files, read the pods in the order given above.
  81.  
  82. But if you aim to compose music with this suite, read this pod, then
  83. L<MIDI::Score> and L<MIDI::Simple>, and then skim the rest.
  84.  
  85. (For your reference, there is also a document in pod format which is
  86. not itself an actual module: L<MIDI::Filespec>.  It is an old version
  87. of the MIDI file specification.)
  88.  
  89. =head1 INTRODUCTION
  90.  
  91. This suite of modules is basically object-oriented, with the exception
  92. of MIDI::Simple.  MIDI opuses ("songs") are represented as objects
  93. belonging to the class MIDI::Opus.  An opus contains tracks, which are
  94. objects belonging to the class MIDI::Track.  A track will generally
  95. contain a list of events, where each event is a list consisting of a
  96. command, a delta-time, and some number of parameters.  In other words,
  97. opuses and tracks are objects, and the events in a track comprise a
  98. LoL (and if you don't know what an LoL is, you must read L<perllol>).
  99.  
  100. Furthermore, for some purposes it's useful to analyze the totality of
  101. a track's events as a "score" -- where a score consists of notes where
  102. each event is a list consisting of a command, a time offset from the
  103. start of the track, and some number of parameters.  This is the level
  104. of abstraction that MIDI::Score and MIDI::Simple deal with.
  105.  
  106. While this suite does provide some functionality accessible only if
  107. you're comfortable with various kinds of references, and while there
  108. are some options that deal with the guts of MIDI encoding, you can (I
  109. hope) get along just fine with just a basic grasp of the MIDI
  110. "standard", and a command of LoLs.  I have tried, at various points in
  111. this documentation, to point out what things are not likely to be of
  112. use to the casual user.
  113.  
  114. =head1 TO DO
  115.  
  116. Maybe have a MIDI cookbook of commonly used short scripts?
  117.  
  118. B<A PLEA>: Currently this suite can only read/write MIDI data from/to
  119. MIDI I<files>.  However, it would be desirable to have realtime access
  120. to a MIDI device -- at least on systems where a MIDI device (whether
  121. thru a hardware port or as a virtual sequencer in a sound card) is
  122. accessable as a virtual file (C</dev/midi0>, C</dev/midi>,
  123. C</dev/sequencer>, or whatever).  However, I have no such MIDI devices
  124. (much less ports) at hand for development and testing.  But if I<you>
  125. have such devices (I'm thinking a Linuxer with a synth hooked to their
  126. MIDI port), and if you want to help me experiment with directly
  127. accessing them from Perl, then please email me.  I already have a
  128. pretty good idea of how it should work -- but as always, the proof is
  129. as much in the pudding as the devil is in the details.
  130.  
  131. =head1 GOODIES
  132.  
  133. The bare module MIDI.pm doesn't I<do> much more than C<use> the
  134. necessary component submodules (i.e., all except MIDI::Simple).  But
  135. it does provide some hashes you might find useful:
  136.  
  137. =over
  138.  
  139. =cut
  140.  
  141. ###########################################################################
  142. # Note numbers => a representation of them
  143.  
  144. =item C<%MIDI::note2number> and C<%MIDI::number2note>
  145.  
  146. C<%MIDI::number2note> correponds MIDI note numbers to a more
  147. comprehensible representation (e.g., 68 to 'Gs4', for G-sharp, octave
  148. 4); C<%MIDI::note2number> is the reverse.  Have a look at the source
  149. to see the contents of the hash.
  150.  
  151. =cut
  152. @number2note{0 .. 127} = (
  153. # (Do)        (Re)         (Mi)  (Fa)         (So)         (La)        (Ti)
  154.  'C0', 'Cs0', 'D0', 'Ds0', 'E0', 'F0', 'Fs0', 'G0', 'Gs0', 'A0', 'As0', 'B0',
  155.  'C1', 'Cs1', 'D1', 'Ds1', 'E1', 'F1', 'Fs1', 'G1', 'Gs1', 'A1', 'As1', 'B1',
  156.  'C2', 'Cs2', 'D2', 'Ds2', 'E2', 'F2', 'Fs2', 'G2', 'Gs2', 'A2', 'As2', 'B2',
  157.  'C3', 'Cs3', 'D3', 'Ds3', 'E3', 'F3', 'Fs3', 'G3', 'Gs3', 'A3', 'As3', 'B3',
  158.  'C4', 'Cs4', 'D4', 'Ds4', 'E4', 'F4', 'Fs4', 'G4', 'Gs4', 'A4', 'As4', 'B4',
  159.  'C5', 'Cs5', 'D5', 'Ds5', 'E5', 'F5', 'Fs5', 'G5', 'Gs5', 'A5', 'As5', 'B5',
  160.  'C6', 'Cs6', 'D6', 'Ds6', 'E6', 'F6', 'Fs6', 'G6', 'Gs6', 'A6', 'As6', 'B6',
  161.  'C7', 'Cs7', 'D7', 'Ds7', 'E7', 'F7', 'Fs7', 'G7', 'Gs7', 'A7', 'As7', 'B7',
  162.  'C8', 'Cs8', 'D8', 'Ds8', 'E8', 'F8', 'Fs8', 'G8', 'Gs8', 'A8', 'As8', 'B8',
  163.  'C9', 'Cs9', 'D9', 'Ds9', 'E9', 'F9', 'Fs9', 'G9', 'Gs9', 'A9', 'As9', 'B9',
  164.  'C10','Cs10','D10','Ds10','E10','F10','Fs10','G10',
  165.   # Note number 69 reportedly == A440, under a default tuning.
  166.   # and note 60 = Middle C
  167. );
  168. %note2number = reverse %number2note;
  169. # Note how I deftly avoid having to figure out how to represent a flat mark
  170. #  in ASCII.
  171.  
  172. ###########################################################################
  173. #  ****     TABLE 1  -  General MIDI Instrument Patch Map      ****
  174. # (groups sounds into sixteen families, w/8 instruments in each family)
  175. #  Note that I call the map 0-127, not 1-128.
  176.  
  177. =item C<%MIDI::patch2number> and C<%MIDI::number2patch>
  178.  
  179. C<%MIDI::number2patch> correponds General MIDI patch numbers
  180. (0 to 127) to English names (e.g., 79 to 'Ocarina');
  181. C<%MIDI::patch2number> is the reverse.  Have a look at the source
  182. to see the contents of the hash.
  183.  
  184. =cut
  185. @number2patch{0 .. 127} = (   # The General MIDI map: patches 0 to 127
  186. #0: Piano
  187.  "Acoustic Grand", "Bright Acoustic", "Electric Grand", "Honky-Tonk",
  188.  "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clav",
  189. # Chrom Percussion
  190.  "Celesta", "Glockenspiel", "Music Box", "Vibraphone",
  191.  "Marimba", "Xylophone", "Tubular Bells", "Dulcimer",
  192.  
  193. #16: Organ
  194.  "Drawbar Organ", "Percussive Organ", "Rock Organ", "Church Organ",
  195.  "Reed Organ", "Accordion", "Harmonica", "Tango Accordion",
  196. # Guitar
  197.  "Acoustic Guitar(nylon)", "Acoustic Guitar(steel)",
  198.  "Electric Guitar(jazz)", "Electric Guitar(clean)",
  199.  "Electric Guitar(muted)", "Overdriven Guitar",
  200.  "Distortion Guitar", "Guitar Harmonics",
  201.  
  202. #32: Bass
  203.  "Acoustic Bass", "Electric Bass(finger)",
  204.  "Electric Bass(pick)", "Fretless Bass",
  205.  "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2",
  206. # Strings
  207.  "Violin", "Viola", "Cello", "Contrabass",
  208.  "Tremolo Strings", "Orchestral Strings", "Orchestral Strings", "Timpani",
  209.  
  210. #48: Ensemble
  211.  "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  212.  "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit",
  213. # Brass
  214.  "Trumpet", "Trombone", "Tuba", "Muted Trumpet",
  215.  "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2",
  216.  
  217. #64: Reed
  218.  "Soprano Sax", "Alto Sax", "Tenor Sax", "Baritone Sax",
  219.  "Oboe", "English Horn", "Bassoon", "Clarinet",
  220. # Pipe
  221.  "Piccolo", "Flute", "Recorder", "Pan Flute",
  222.  "Blown Bottle", "Skakuhachi", "Whistle", "Ocarina",
  223.  
  224. #80: Synth Lead
  225.  "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  226.  "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)",
  227. # Synth Pad
  228.  "Pad 1 (new age)", "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)",
  229.  "Pad 5 (bowed)", "Pad 6 (metallic)", "Pad 7 (halo)", "Pad 8 (sweep)",
  230.  
  231. #96: Synth Effects
  232.  "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)", "FX 4 (atmosphere)",
  233.  "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  234. # Ethnic
  235.  "Sitar", "Banjo", "Shamisen", "Koto",
  236.  "Kalimba", "Bagpipe", "Fiddle", "Shanai",
  237.  
  238. #112: Percussive
  239.  "Tinkle Bell", "Agogo", "Steel Drums", "Woodblock",
  240.  "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  241. # Sound Effects
  242.  "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet",
  243.  "Telephone Ring", "Helicopter", "Applause", "Gunshot",
  244. );
  245. %patch2number = reverse %number2patch;
  246.  
  247. ###########################################################################
  248. #     ****    TABLE 2  -  General MIDI Percussion Key Map    ****
  249. # (assigns drum sounds to note numbers. MIDI Channel 9 is for percussion)
  250. # (it's channel 10 if you start counting at 1.  But WE start at 0.)
  251.  
  252. =item C<%MIDI::notenum2percussion> and C<%MIDI::percussion2notenum>
  253.  
  254. C<%MIDI::notenum2percussion> correponds General MIDI Percussion Keys
  255. to English names (e.g., 56 to 'Cowbell') -- but note that only numbers
  256. 35 to 81 (inclusive) are defined; C<%MIDI::percussion2notenum> is the
  257. reverse.  Have a look at the source to see the contents of the hash.
  258.  
  259. =cut
  260.  
  261. @notenum2percussion{35 .. 81} = (
  262.  'Acoustic Bass Drum', 'Bass Drum 1', 'Side Stick', 'Acoustic Snare',
  263.  'Hand Clap',
  264.  
  265.  # the forties 
  266.  'Electric Snare', 'Low Floor Tom', 'Closed Hi-Hat', 'High Floor Tom',
  267.  'Pedal Hi-Hat', 'Low Tom', 'Open Hi-Hat', 'Low-Mid Tom', 'Hi-Mid Tom',
  268.  'Crash Cymbal 1',
  269.  
  270.  # the fifties
  271.  'High Tom', 'Ride Cymbal 1', 'Chinese Cymbal', 'Ride Bell', 'Tambourine',
  272.  'Splash Cymbal', 'Cowbell', 'Crash Cymbal 2', 'Vibraslap', 'Ride Cymbal 2',
  273.  
  274.  # the sixties
  275.  'Hi Bongo', 'Low Bongo', 'Mute Hi Conga', 'Open Hi Conga', 'Low Conga',
  276.  'High Timbale', 'Low Timbale', 'High Agogo', 'Low Agogo', 'Cabasa',
  277.  
  278.  # the seventies
  279.  'Maracas', 'Short Whistle', 'Long Whistle', 'Short Guiro', 'Long Guiro',
  280.  'Claves', 'Hi Wood Block', 'Low Wood Block', 'Mute Cuica', 'Open Cuica',
  281.  
  282.  # the eighties
  283.  'Mute Triangle', 'Open Triangle',
  284. );
  285. %percussion2notenum = reverse %notenum2percussion;
  286.  
  287. ###########################################################################
  288.  
  289. =back
  290.  
  291. =head1 BRIEF GLOSSARY
  292.  
  293. This glossary defines just a few terms, just enough so you can
  294. (hopefully) make some sense of the documentation for this suite of
  295. modules.  If you're going to do anything serious with these modules,
  296. however, you I<should really> invest in a good book about the MIDI
  297. standard -- see the References.
  298.  
  299. B<channel>: a logical channel to which control changes and patch
  300. changes apply, and in which MIDI (note-related) events occur.
  301.  
  302. B<control>: one of the various numeric parameters associated with a
  303. given channel.  Like S registers in Hayes-set modems, MIDI controls
  304. consist of a few well-known registers, and beyond that, it's
  305. patch-specific and/or sequencer-specific.
  306.  
  307. B<delta-time>: the time (in ticks) that a sequencer should wait
  308. between playing the previous event and playing the current event.
  309.  
  310. B<meta-event>: any of a mixed bag of events whose common trait is
  311. merely that they are similarly encoded.  Most meta-events apply to all
  312. channels, unlike events, which mostly apply to just one channel.
  313.  
  314. B<note>: my oversimplistic term for items in a score structure.
  315.  
  316. B<opus>: the term I prefer for a piece of music, as represented in
  317. MIDI.  Most specs use the term "song", but I think that this
  318. falsely implies that MIDI files represent vocal pieces.
  319.  
  320. B<patch>: an electronic model of the sound of a given notional
  321. instrument.
  322.  
  323. B<running status>: a form of modest compression where an event lacking
  324. an event command byte (a "status" byte) is to be interpreted as having
  325. the same event command as the preceding event -- which may, in turn,
  326. lack a status byte and may have to be interpreted as having the same
  327. event command as I<its> previous event, and so on back.
  328.  
  329. B<score>: a structure of notes like an event structure, but where
  330. notes are represented as single items, and where timing of items is
  331. absolute from the beginning of the track, instead of being represented
  332. in delta-times.
  333.  
  334. B<song>: what some MIDI specs call a song, I call an opus.
  335.  
  336. B<sequencer>: a device or program that interprets and acts on MIDI
  337. data.  This prototypically refers to synthesizers or drum machines,
  338. but can also refer to more limited devices, such as mixers or even
  339. lighting control systems.
  340.  
  341. B<status>: a synonym for "event".
  342.  
  343. B<sysex>: a chunk of binary data encapsulated in the MIDI data stream,
  344. for whatever purpose.
  345.  
  346. B<text event>: any of the several meta-events (one of which is
  347. actually called 'text_event') that conveys text.  Most often used to
  348. just label tracks, note the instruments used for a track, or to
  349. provide metainformation about copyright, performer, and piece title
  350. and author.
  351.  
  352. B<tick>: the timing unit in a MIDI opus.
  353.  
  354. B<variable-length encoding>: an encoding method identical to what Perl
  355. calls the 'w' (BER, Basic Encoding Rules) pack/unpack format for
  356. integers.
  357.  
  358. =head1 REFERENCES
  359.  
  360. Christian Braut.  I<The Musician's Guide to Midi.>  ISBN 0782112854.
  361. [This one is indispensible --SMB]
  362.  
  363. Langston, Peter S.  1998. "Little Music Languages", p.587-656 in:
  364. Salus, Peter H,. editor in chief, /Handbook of Programming Languages/,
  365. vol.  3.  MacMillan Technical, 1998.  [The volume it's in is probably
  366. not worth the money, but see if you can at least glance at this
  367. article anyway.  It's not often you see 70 pages written on music
  368. languages. --SMB]
  369.  
  370. I'll keep a list of other references and good stuff at
  371. the URL C<http://www.speech.cs.cmu.edu/~sburke/pub/perl_midi/>
  372.  
  373. =head1 COPYRIGHT 
  374.  
  375. Copyright (c) 1998-2002 Sean M. Burke. All rights reserved.
  376.  
  377. This library is free software; you can redistribute it and/or
  378. modify it under the same terms as Perl itself.
  379.  
  380. =head1 AUTHOR
  381.  
  382. Sean M. Burke C<sburke@cpan.org>
  383.  
  384. =cut
  385.  
  386. ###########################################################################
  387. sub _dump_quote {
  388.   # Used variously by some MIDI::* modules.  Might as well keep it here.
  389.   my @stuff = @_;
  390.   return
  391.     join(", ",
  392.     map
  393.      { # the cleaner-upper function
  394.        if(!length($_)) { # empty string
  395.          "''";
  396.        } elsif(
  397.                    $_ eq '0' or m/^-?(?:[1-9]\d*)$/s  # integers
  398.  
  399.            # Was just: m/^-?\d+(?:\.\d+)?$/s
  400.                    # but that's over-broad, as let "0123" thru, which is
  401.                    # wrong, since that's octal 0123, == decimal 83.
  402.  
  403.                    # m/^-?(?:(?:[1-9]\d*)|0)(?:\.\d+)?$/s and $_ ne '-0'
  404.                    # would let thru all well-formed numbers, but also
  405.                    # non-canonical forms of them like 0.3000000.
  406.                    # Better to just stick to integers I think.
  407.        ) {
  408.          $_;
  409.        } elsif( # text with junk in it
  410.           s<([^\x20\x21\x23\x27-\x3F\x41-\x5B\x5D-\x7E])>
  411.            <'\\x'.(unpack("H2",$1))>eg
  412.          ) {
  413.          "\"$_\"";
  414.        } else { # text with no junk in it
  415.          s<'><\\'>g;
  416.          "\'$_\'";
  417.        }
  418.      }
  419.      @stuff
  420.     );
  421. }
  422. ###########################################################################
  423.  
  424. 1;
  425.  
  426. __END__
  427.