Determining Clojure Version
Problem
How do I tell which version of Clojure I am using?
Solution
Evaluate the variable clojure.core/*clojure-version* or the function clojure.core/clojure-version.
(doc *clojure-version*)
-------------------------
clojure.core/*clojure-version*
nil
The version info for Clojure core, as a map containing :major :minor
:incremental and :qualifier keys. Feature releases may increment
:minor and/or :major, bugfix releases will increment :incremental.
Possible values of :qualifier include "GA", "SNAPSHOT", "RC-x" "BETA-x"
(doc clojure-version)
-------------------------
clojure.core/clojure-version
([])
Returns clojure version as a printable string.
Determining Number of Available Processors
Problem
How do I tell how many processors my computer has?
Solution
Ask the Java runtime system:
(.availableProcessors (Runtime/getRuntime)) => 2
Screen Capture
Problem
How do I do a screen capture using Clojure?
Solution
Use the createScreenCapture() method of java.awt.Robot:
(import '(java.awt AWTException Robot Rectangle Toolkit)
'(java.awt.image BufferedImage)
'(java.io File IOException)
'(javax.imageio ImageIO))
(defn screen-grab [file-name]
(let [img-type (second (re-find (re-matcher #"\.(\w+)$" file-name)))
capture (.createScreenCapture (Robot.)
(Rectangle. (.getScreenSize (Toolkit/getDefaultToolkit))))
file (File. file-name)]
(ImageIO/write capture img-type file)))
The variable capture is an instance of java.awt.image.BufferedImage, and ImageIO.write() outputs it as a file, typically either as JPEG/JPG or PNG.
Playing a Sound File
Problem
How do I play a sound file from my program?
Solution
The simple way to play a .wav or MIDI file is to use the method Applet.newAudioClip() to create a java.applet.AudioClip instance and call its play() method:
(import '(java.applet Applet)
'(java.io File)
'(java.net URL))
(defn play-url [url-string]
(.play (Applet/newAudioClip (URL. url-string))))
(defn play-file [file-name]
(let [absolute-name (.getAbsolutePath (File. file-name))
url-string (str "file://" absolute-name)]
(play-url url-string)))
The newAudioClip() method expects a java.net.URL instance, so for local files we have to add the prefix "file://".
(play-url "http://www.talkingwav.com/cartoon/porky_pig_02.wav")
(play-file "beanears.mid")
Back to Clojure Cookbook: Table of Contents
With the sound file example, wouldn't it be better for play-file to call play-url to avoid duplication?
(defn play-file [file-name]
(let [absolute-name (.getAbsolutePath (File. file-name))
url (str "file://" absolute-name)]
(play-url url)))
Good point, Sean. Fixed it. Thanks.
Thanks David, this was just what I needed.
Post preview:
Close preview