Skip to content

Instantly share code, notes, and snippets.

@alandipert
Created March 31, 2010 12:37
Show Gist options
  • Save alandipert/350253 to your computer and use it in GitHub Desktop.
Save alandipert/350253 to your computer and use it in GitHub Desktop.
Play music with Clojure and javax.sound.midi
(import '(javax.sound.midi MidiSystem Synthesizer))
(defn play-note [synth channel note-map]
(let [{:keys [note velocity duration]
:or {note 60
velocity 127
duration 1000}} note-map]
(. channel noteOn note velocity)
(Thread/sleep duration)
(. channel noteOff note)))
(defn play-notes
[notes]
(with-open [synth (doto (MidiSystem/getSynthesizer) .open)]
(let [channel (aget (.getChannels synth) 0)]
(doseq [note notes]
(play-note synth channel note)))))
(defn play-c-major-scale []
(let [c-major [0 2 4 5 7 9 11 12]
c-major-notes (map #(hash-map :note (+ % 60) :duration 400) c-major)]
(play-notes (concat c-major-notes
(rest (reverse c-major-notes))))))
(play-c-major-scale)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment