Skip to content

Instantly share code, notes, and snippets.

@nexneo
Forked from mauritslamers/gist:143207
Created July 8, 2009 21:30
Show Gist options
  • Save nexneo/143209 to your computer and use it in GitHub Desktop.
Save nexneo/143209 to your computer and use it in GitHub Desktop.
;; javasound
(import '(javax.sound.sampled AudioSystem Line DataLine DataLine$Info SourceDataLine TargetDataLine AudioFormat))
(defn get-audio-format [samplerate bitsize channels]
(new AudioFormat samplerate bitsize channels true false))
(defn get-source-data-line-info [audioformat]
(new DataLine$Info SourceDataLine audioformat))
(defn get-source-data-line [datalineinfo]
(AudioSystem/getLine datalineinfo))
(defn get-sound-out [samplefreq bitsize channels buffersize]
(let [
audioformat (get-audio-format samplefreq bitsize channels)
sourcedatalineinfo (get-source-data-line-info audioformat)
#^SourceDataLine sourcedataline (get-source-data-line sourcedatalineinfo)
]
(.open sourcedataline audioformat buffersize)
(.start sourcedataline)
sourcedataline))
(defn duration-in-samples [samplerate duration-in-ms]
(* samplerate (/ duration-in-ms 1000))
)
(defn lazy-sine [frequency volume samplerate duration-in-ms]
(let
[
one-over-samplerate (/ 1 samplerate)
number-of-samples (duration-in-samples samplerate duration-in-ms)
sine-factor (* 2 Math/PI one-over-samplerate frequency)
]
(map #(* volume (Math/sin (* sine-factor %))) (range number-of-samples))))
(defn lazy-silence [samplerate duration-in-ms]
(let
[number-of-samples (duration-in-samples samplerate duration-in-ms)]
(take number-of-samples (cycle [0.0]))))
(defn float-to-two-bytes [value]
(let [ intval (int (* value 32765)) ]
(if (and (>= value -1 ) (<= value 1))
[ (byte intval) (byte (bit-shift-right intval 8)) ])))
(defn convert-float-to-byte-array [floatseq]
(into-array Byte/TYPE
(reduce conj []
(mapcat #(float-to-two-bytes %) floatseq))))
(def soundout (get-sound-out 44100 16 1 8192))
(def toon (lazy-sine 440 0.6 44100 500))
(def toonbytes (convert-float-to-byte-array toon))
(defn play-sound [soundout buffer]
(let [
output #^SourceDataLine soundout
]
(try (.write output buffer 0 (count buffer)))))
;; model of how to write sound to the soundout
;;(try (.write soundout (into-array Byte/TYPE (map byte (take 15000 sine))) 0 15000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment