Skip to content

A background polyphonic music generator for Teensy, using wave table synthesis

License

Notifications You must be signed in to change notification settings

LenShustek/Playtune_samp

Repository files navigation

************************************************************************************

     Playtune_samp: A tune generator that uses sample-based
     synthesis to play a polyphonic musical score.


                         About Playtune, generally

   Playtune is a family of music players for Arduino-like microcontrollers. They
   each intepret a bytestream of commands that represent a polyphonic musical
   score, and play it using different techniques.

   (1) The original Playtune that was first released in 2011 uses a separate hardware timer
   to generate a square wave for each note played simultaneously. The timers run at twice
   the frequency of the note being played, and the interrupt routine flips the output bit.
   It can play only as many simultaneous notes as there are timers available. The sound
   quality? Buzzy square waves.
   https://github.com/LenShustek/arduino-playtune

   (2) The second ("polling") version uses only one hardware timer that interrupts often,
   by default at 20 Khz, or once every 50 microseconds. The interrupt routine determines
   which, if any, of the currently playing notes need to be toggled. It also implements
   primitive volume modulation by changing the duty cycle of the square wave.
   The advantage over the first version is that the number of simultaneous notes is not
   limited by the number of timers, only by the number of output pins. The sound quality
   is still "buzzy square waves".
   https://github.com/LenShustek/playtune_poll

   (3) This third version also uses only one hardware timer interrupting frequently, but
   uses the hardware digital-to-analog converter on high-performance microntrollers like
   the Teensy to generate an analog wave that is the sum of stored samples of sounds. The
   samples are scaled to the right frequency and volume, and any number of instrument
   samples can be used and mapped to MIDI patches. The sound quality is much better,
   although not in league with real synthesizers. This currently only support Teensy.
   https://github.com/LenShustek/playtune_samp

   For all these versions, once a score starts playing, the processing happens in
   the interrupt routine.  Any other "real" program can be running at the same time
   as long as it doesn't use the timer or the output pins that Playtune is using.

   **** Details about this version: Playtune_samp

   This is currently implemented only for the PJRC Teensy LC and Teensy 3.x
   microcontrollers, because they have an D-to-A converter and are fast enough.

   You'll see some experimental code for Arudinos using PCM D-to-A, but it's not fast
   enough yet and needs more work. A demotivating factor is that, even if it works,
   it's hard to get enough  wave tables and scores to fit in 32K, vs the 128K or 256K
   in a Teensy. (Can you tell I'm a Teensy fan?)

   (For an example of some great "extreme programming" for efficiency in music
   generation on small 8-bit processors, see Erico Colombini's "play-v6" code, and his
   nice blog  tutorial articles:  http://www.erix.it/play-v6/,
   http://www.quintadicopertina.com/enricocolombini/language/en/.)

   There is support in this version for volume modulation, instrument choice, and percussion.

   (1) If the ASSUME_VOLUME compile-time switch is set to 1, or if the optional file
   header file indicates that volume information is present, then we interpret MIDI
   "velocity" information to scale the analog output of each tone generator separately.
   The bytestream volume information can be generated by Miditones with the -v option.

   (2) As we find instrument change instructions (Ct ii) in the bytestream, we map MIDI
   patches to a variety of prerecorded instrument samples. The bytestream instrument
   information can be generated by Miditones with the -i option.

   (2) If we find note numbers greater than 127, we interpret them as having come from
   MIDI channel 9 (10 if you start counting with 1) as percussion sounds, which we play
   as single non-repeated samples. Those notes are relocated from 0..127 to 128.255
   by Miditones with the -pt option.

   It's possible to (barely) hear the music just by connecting the analog output pin
   to a speaker through a 50-ohm resistor. But you'll really want to use an amplified
   speaker. I use this one: https://www.amazon.com/gp/product/B00CWBABP4.
   A little low-pass filtering with a resistor and capacitor helps too.

   **** Programming with Playtune_poll

   Unlike the original Playtune, this is not configured as a library because we make
   compile-time changes for pin assignments. You should create a sketch directory
   with the following files in it:

     Playtune_samp.ino        This file, which has most of the code
     Playtune_samp.h          The header file, which defines the output pin configuration
     Playtune_samp_waves.ino  The file that contains the stored sound samples
     Playtune_samp_test.ino   The main program, which contains the score(s) you wish to
                               play, and any other code you want to run.

   You must change the #define at the begininng of Playtune_samp.h to indicate which
   board you are compiling for, in addition to setting that in the Arduino/Teenyduino
   IDE Tools/Board menu.

   You can use up to MAX_CHANS tone generators, as defined in Playtune_samp.h.
   There is some inefficiency if MAX_CHANS is much larger than the number of tone
   generators actually being used if the file doesn't have a -d header to tell it.

   We also use the TimerOne library files, which you can get at
   http://playground.arduino.cc/Code/Timer1 and put into your Arduino library
   directory, or just put in the directory with the other files.

   There are four public functions and one public variable that you can use
   in your runtime code in Playtune_samp_test.ino.

   void tune_start_timer(int microseconds)

    This is optional. Call it to set how often notes should be checked for transitions,
    from 5 to 100 microseconds. If you don't call it, we'll pick something that seems
    appropriate from the type of microcontroller and the frequency it's running at.

   void tune_playscore(byte *score)

     Call this pointing to a "score bytestream" to start playing a tune.  It will
     only play as many simultaneous notes as you have defined tone generators;
     any more will be ignored.  See below for the format of the score bytestream.

   boolean tune_playing

     This global variable will be "true" if a score is playing, and "false" if not.
     You can use this to see when a score has finished.

   void tune_stopscore()

     This will stop a currently playing score without waiting for it to end by itself.

   void tune_stop_timer()

     This stops playing and also stops the timer interrupt.
     Do this when you don't want to play any more tunes.


   *****  The score bytestream  *****

   The bytestream is a series of commands that can turn notes on and off, or
   start a waiting period until the next note change.  Here are the details, with
   numbers shown in hexadecimal.

   If the high-order bit of the byte is 1, then it is one of the following commands:

     9t nn  Start playing note nn on tone generator t.  Generators are numbered
            starting with 0.  The notes numbers are the MIDI numbers for the chromatic
            scale, with decimal 60 being Middle C, and decimal 69 being Middle A
            at 440 Hz.  The highest note is decimal 127 at about 12,544 Hz. except
            that percussion notes (instruments, really) range from 128 to 255.

            [vv]  If ASSUME_VOLUME is set to 1, or the file header tells us to,
            then we expect a third byte with the volume ("velocity") value from 1 to
            127. You can generate this from Miditones with the -v option.
            (Everything breaks for headerless files if the assumption is wrong!)

     8t     Stop playing the note on tone generator t.

     Ct ii  Change tone generator t to play instrument ii from now on. Miditones will
            generate this with the -i option.

     F0     End of score: stop playing.

     E0     End of score: start playing again from the beginning.

   If the high-order bit of the byte is 0, it is a command to wait.  The other 7 bits
   and the 8 bits of the following byte are interpreted as a 15-bit big-endian integer
   that is the number of milliseconds to wait before processing the next command.
   For example,

     07 D0

   would cause a wait of 0x07d0 = 2000 decimal millisconds or 2 seconds.  Any tones
   that were playing before the wait command will continue to play.

   Playtune bytestream files generated by later version of the Miditones progam using
   the -d option begin with a small header that describe what optional data is present
   in the file. This makes the file more self-describing, and this version of Playtune
   uses that if it is present.

    'Pt'   2 ascii characters that signal the presence of the header
     nn    The length (in one byte) of the entire header, 6..255
     ff1   A byte of flag bits, three of which are currently defined:
               80 velocity information is present
               40 instrument change information is present
               20 translated percussion notes are present
     ff2    Another byte of flags, currently undefined
     tt     The number (in one byte) of tone generators actually used in this music.
            We use that the scale the volume when combining simulatneous notes.

     Any subsequent header bytes covered by the count, if present, are currently undefined
     and are ignored.

   The score is stored in Flash memory ("PROGMEM") along with the program, because
   there's a lot more of that than data memory.


   *****  Where does the score data come from?  *****

   Well, you can write the score by hand from the instructions above, but that's
   pretty hard.  An easier way is to translate MIDI files into these score commands,
   and I've written a program called "Miditones" to do that.  See the separate
   documentation for that program, which is also open source at
   https://github.com/lenshustek/miditones
   The best Miditones options to use for this version of Playtune are: -v -i -pt -d
   And, of course, if you want more than 6 tone generators, -tn


   *****  Nostalgia from me  *****

   Writing Playtune was a lot of fun, because it essentially duplicates what I did
   as a graduate student at Stanford University in about 1973.  That project used the
   then-new Intel 8008 microprocessor, plus three hardware square-wave generators that
   I built out of 7400-series TTL.  The music compiler was written in Pascal and read
   scores that were hand-written in a notation I made up, which looked something like
   this:     C  Eb  4G  8G+  2R  +  F  D#
   This was before MIDI had been invented, and anyway I wasn't a pianist so I would
   not have been able to record my own playing.  I could barely read music well enough
   to transcribe scores, but I slowly did quite a few of them. MIDI is better!

   Len Shustek, originally 4 Feb 2011,
   ...updated for the sampling version in August 2016.

About

A background polyphonic music generator for Teensy, using wave table synthesis

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages