midisynth.frink

Download or view midisynth.frink in plain text format


// Uses Java calls to play notes via MIDI synthesis.  This requires a JVM that
// actually *has* a MIDI synthesizer (e.g. Oracle's JVM works,
// OpenJDK may not.)

synth = callJava["javax.sound.midi.MidiSystem","getSynthesizer",[]]
synth.open[]
chan = synth.getChannels[]

// This part is unnecessary but it shows how to change instruments.
soundbank = synth.getDefaultSoundbank[]
instruments = soundbank.getInstruments[]
instrument = rand[instruments]
patch = instrument.getPatch[]
(chan@0).programChange[patch.getBank[], patch.getProgram[]]

// Dump names of instruments?
for i=0 to length[instruments]-1
   println["$i\t" + (instruments@i).getName[]]

println["Random instrument for channel 0: " + instrument.getName[]]

sleep[1 s]   // Sound seems choppy if we play too soon?


// Major pentatonic scale
pentMajor = [0,2,4,7,9]    // I also see [0,2,5,7,9]
// Minor pentatonic scale
pentMinor = [0,3,5,7,10]

key = 60   // Start around middle C (these are MIDI note definitions)

simultaneousNotes = 3
lastNotes = new RingBuffer[simultaneousNotes]

for n=0 to 50
{
   keyChange = rand[[0,0,0,0,0,0,0,0,+7,-5,+5,-7]]   // Follows "circle of fifths"
   key = key + keyChange
   if keyChange != 0
      println["Key change: $key"]

   for note = 0 to 3    // Notes per measure without keychange
   {
      for sim = 0 to simultaneousNotes-1
      {
         mid = rand[0,10]
         // Play each note on a separate channel.
         note = key + (mid div 5) * 12 + pentMajor@(mid mod 5)
         if (length[lastNotes] > 0)
            (chan@sim).noteOff[lastNotes.pop[]]
         lastNotes.push[note]
         (chan@sim).noteOn[note, 93]
      }
      sleep[.5 s]
   }
}

sleep[9 s]  // Sleep while the notes play.


Download or view midisynth.frink in plain text format


This is a program written in the programming language Frink.
For more information, view the Frink Documentation or see More Sample Frink Programs.

Alan Eliasen was born 20217 days, 15 hours, 27 minutes ago.