On Mon, Jul 27, 2009 at 9:00 PM, Rayne <disciplera...@gmail.com> wrote:

>
> I've googled around, and found several ways to do this in Java, but
> I've not been successful in translating the less-complex examples. I'm
> wondering, how would an experienced Clojurian go about doing this in
> Clojure?


On my system, the following works even for mp3 files and other compressed
ones, if the appropriate JavaSound plugins are installed. It should work for
plain wavs with a bare-bones Java 6/Clojure install. It blocks, so you might
want to invoke it in a separate thread/via an Agent in actual practice. (It
might also be instructive as an example of Java interop involving things
like byte buffers.)

(defn play
  "Plays an audio file. Blocks until playback is complete."
  [file]
  (let [f (if (instance? java.io.File file) file (java.io.File. file))]
    (with-open [aif (javax.sound.sampled.AudioSystem/getAudioInputStream f)
                ais (javax.sound.sampled.AudioSystem/getAudioInputStream
                      javax.sound.sampled.AudioFormat$Encoding/PCM_SIGNED
aif)]
      (let [af (.getFormat ais)]
        (with-open [line (javax.sound.sampled.AudioSystem/getSourceDataLine
af)]
          (.open line af)
          (let [bufsize (.getBufferSize line)
                buf (into-array Byte/TYPE (repeat bufsize (byte 0)))]
            (.start line)
            (loop []
              (let [br (.read ais buf 0 bufsize)]
                (if-not (= -1 br)
                  (do
                    (.write line buf 0 br)
                    (recur))
                  (doto line (.drain) (.stop)))))))))))

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to