Created
May 20, 2012 14:34
-
-
Save Madsy/2758323 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns audiofun.core | |
(:import [java.lang Math] | |
[javax.sound.sampled AudioFormat | |
AudioInputStream AudioSystem Clip DataLine LineEvent LineListener]) | |
) | |
(defn lowest-byte [^long s] | |
(unchecked-byte (bit-and s 255))) | |
(defn highest-byte [^long s] | |
(unchecked-byte (bit-and (bit-shift-right s 8) 255))) | |
(defn sin[^double f ^double t] | |
(let [s (Math/sin (* 2 Math/PI f t))] | |
(/ (Math/floor (* s 65535)) 65535))) | |
(defn to-audio-array [coll] | |
"Split 16-bit shorts into two bytes, little endian" | |
(byte-array | |
(flatten (map (juxt lowest-byte highest-byte) coll)))) | |
(defn sin-sequence | |
[^double vol ^double freq ^double t] | |
"vol: Volume in the range [0 1] inclusive" | |
"freq: Frequency of sine wave. 440 for A-4" | |
"t: Duration in seconds." | |
(for [dur (range 0 (* t 44100))] | |
(unchecked-short (* 32767.0 vol (sin freq (float (/ dur 44100))))))) | |
(defn play-sample [arr] | |
(let [samplelen (alength arr) | |
audioformat (new AudioFormat | |
44100.0 ;Samplerate (float) | |
16 ; Bits per sample (int) | |
1 ; Number of channels (int) | |
true ;Signed? (boolean) | |
false ;Big endian? (boolean) | |
) | |
strm (new AudioInputStream | |
(new ByteArrayInputStream arr 0 samplelen) | |
audioformat samplelen) | |
clip (doto (AudioSystem/getClip) | |
(.open strm) ; This throws IllegalArgumentException. And it does indeed take an AudioInputStream | |
(.loop Clip/LOOP_CONTINUOUSLY) | |
(.start))] | |
#(. clip stop)) | |
) | |
(def sin-sample (to-audio-array (sin-sequence 0.5 440.0 1.0))) | |
(def stop-sample (playsample sin-sample)) | |
; This yields: | |
; core.clj:51:1: | |
; error: java.lang.IllegalArgumentException: Invalid format, compiling:(core.clj:51) | |
; Class overview: | |
; http://docs.oracle.com/javase/7/docs/api/javax/sound/sampled/AudioSystem.html | |
; http://docs.oracle.com/javase/7/docs/api/javax/sound/sampled/AudioInputStream.html | |
; http://docs.oracle.com/javase/7/docs/api/javax/sound/sampled/AudioFormat.html | |
; http://docs.oracle.com/javase/7/docs/api/javax/sound/sampled/Clip.html | |
; http://docs.oracle.com/javase/7/docs/api/javax/sound/sampled/package-summary.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment