(ns clojure-scale.core)


;; taylodl 2014
;;Making Music with Clojure – An Introduction to MIDI
;;https://taylodl.wordpress.com/2014/01/21/making-music-with-clojure-an-introduction-to-midi/


(defn getSynthPlayer [channelNbr instrumentNbr]
     "Initialize synthesizer and return play function"
     (let [synth (javax.sound.midi.MidiSystem/getSynthesizer)]
       (do
         (.open synth) ; Open synth before using
           (let [channels (.getChannels synth)
                 instruments (.. synth getDefaultSoundbank getInstruments)]
             (do
               (let [channel (nth channels channelNbr)
                     instrument (nth instruments instrumentNbr)]
                 (println "Instrument" instrumentNbr "is" (.getName instrument))
                 (.loadInstrument synth instrument)
                 (.programChange channel instrumentNbr) ; Lots of blogs never mentioned this!
                 (fn [volume note duration] ; play function
                   (do
                     (.noteOn channel note volume)
                     (Thread/sleep duration)
                     (.noteOff channel note)))))))))



(defn play [synthPlayer accVolume seqNotes]
  "Play note sequence at specified starting volume on player obtained via getSynthPlayer"
  (if (or (nil? seqNotes) (empty? seqNotes)) nil
    (let [[note duration {:keys [vol_adj] :or {vol_adj 0}}] (first seqNotes)
          volume (+ accVolume vol_adj)]
      (do
        (synthPlayer volume note duration) ; invoke function returned from getSynthPlayer
        (recur synthPlayer volume (rest seqNotes))))))


(def chromatic-scale '([60 250] [62 250 {:vol_adj +2}] [64 250 {:vol_adj +2}]  [65 250 {:vol_adj +2}] 
                                [67 250 {:vol_adj +2}]  [69 250 {:vol_adj +2}]  [71 250 {:vol_adj +2}] 
                                [72 250 {:vol_adj +2}] [72 250] 
                                [71 250 {:vol_adj -2}] [69 250 {:vol_adj -2}] 
                                [67 250 {:vol_adj -2}] [65 250 {:vol_adj -2}] 
                                [64 250 {:vol_adj -2}] [62 250 {:vol_adj -2}] 
                                [60 750 {:vol_adj -2}]))

(def joy-to-the-world
'([77 660] [76 495] [74 165] [72 990] [70 330] [69 660] [67 660] [65 990]
[72 330] [74 990] [74 330] [76 990] [76 330] [77 990]
[77 330] [77 330] [76 330] [74 330] [72 330] [72 495] [70 165] [69 330] [77 330] [77 330] [76 330] [74 330] [72 330] [72 495] [70 165] [69 330]
[69 330] [69 330] [69 330] [69 330] [69 165] [70 165] [72 990]
[70 165] [69 165] [67 330] [67 330] [67 330] [67 165] [69 165] [70 990]
[69 165] [67 165] [65 330] [77 660] [74 330] [72 495] [70 165] [69 330] [70 330] [69 660] [67 660] [65 1980]))

(defn -main
  "Right now we play the chromatic scale using the instrument provided"
  [instrument]
  (let [synthPlayer (getSynthPlayer 2 instrument)]
    (play synthPlayer 80 chromatic-scale)
    (play synthPlayer 80 joy-to-the-world)
    ))

(-main 0);piano
(-main 40);violin