Wishful Coding

Didn't you ever wish your
computer understood you?

Generative Music

It’s been a long time since I played with Overtone. What I’ve always wanted to do is generate music automatically. Today I ran into jFugue, which makes this really easy, listen to this:

</param> </param> </embed>

Markov generated music by pepijndevos

I just took some music from wikifonia, constructed a Markov-chain and did a random note-walk.

This could work just as well with Overtone, but I used jFugue because it comes with a parser for MusicXML files.

To run the code below, you need to have jFugue on the classpath. Then just pipe a couple of notes from generate into play.

(ns ponger.core
  (:require clojure.string))

(defn inflate-mxl [file]
  (let [z (java.util.zip.ZipFile. file)]
    (slurp
      (.getInputStream z
        (.nextElement (.entries z))))))

(defn parse-musicxml [file]
  (let [parser   (org.jfugue.parsers.MusicXmlParser.)
        renderer (org.jfugue.MusicStringRenderer.)]
    (.addParserListener parser renderer)
    (.parse parser (inflate-mxl file))
    (.getPattern renderer)))

(defn notes [tokens]
  (filter #(re-matches #"[A-GR].*" %) tokens))

(defn voices [tokens]
  (let [[f [_ & r]] (split-with (complement #(.startsWith % "V")) tokens)]
    (when (seq f)
      (cons f (voices r)))))

(defn make-chain [tokens]
  (into {}
    (for [[k slice] (group-by first (partition 2 1 tokens))]
      [k (map last slice)])))

(defn walk-chain [chain start]
  (let [nxt (rand-nth
              (get chain start
                   (apply concat (vals chain))))]
    (cons
      nxt
      (lazy-seq
        (walk-chain chain nxt)))))

(defn generate [path]
  (-> path
    parse-musicxml
    (.getTokens)
    notes
    make-chain
    (walk-chain nil)))

(defn play [token-seq]
  (let [player (org.jfugue.StreamingPlayer.)]
    (doseq [token token-seq]
      (.stream player token))))

(defn save [token-seq path]
  (.saveMidi (org.jfugue.Player.)
         (clojure.string/join " " token-seq)
         (java.io.File. path)))

NIO in Clojure

So, I’m playing with the idea of writing a little webserver in Clojure, much like those asynchronous Python ones like Twisted and Tornado, but actually I’m just writing this to play with my new blog.

There you have the code, not as a gist this time. The code actually lives in a separate file on Github, and is included here by a few lines of Liquid markup.

This code was modeled after this Java code. If you have anything interesting to say about this code, NIO, webservers or Clojure, I’d love to hear from you.

(ns nio
  (:import
     [java.net
      InetSocketAddress]
     [java.nio
      ByteBuffer
      CharBuffer]
     [java.nio.channels
      ServerSocketChannel
      Selector
      SelectionKey]
     [java.nio.charset
      Charset]))

(def *buffer* (ByteBuffer/allocate 16384))

(defn selector [server-socket-channel]
  (let [selector (Selector/open)]
    (.register server-socket-channel selector SelectionKey/OP_ACCEPT)
    selector))

(defn setup [port]
  (let [server-socket-channel (ServerSocketChannel/open)
        _ (.configureBlocking server-socket-channel false)
        server-socket (.socket server-socket-channel)
        inet-socket-address (InetSocketAddress. port)]
    (.bind server-socket inet-socket-address)
    [(selector server-socket-channel)
     server-socket]))

(defn state= [state channel]
  (= (bit-and (.readyOps channel) state) state))

(defn buffer->string
  ([byte-buffer]
   (buffer->string byte-buffer (Charset/defaultCharset)))
  ([byte-buffer charset]
   (.toString (.decode charset byte-buffer))))

(defn string->buffer
  ([string]
   (string->buffer string (Charset/defaultCharset)))
  ([string charset]
   (.encode charset string)))

(defn accept-connection [server-socket selector]
  (let [channel (-> server-socket (.accept) (.getChannel))]
    (println "Connection from" channel)
    (doto channel
      (.configureBlocking false)
      (.register selector SelectionKey/OP_READ))))

(defn read-socket [selected-key]
  (let [socket-channel (.channel selected-key)]
    (.clear *buffer*)
    (.read socket-channel *buffer*)
    (.flip *buffer*)
    (if (= (.limit *buffer*) 0)
      (do
        (println "Lost connection from" socket-channel)
        (.cancel selected-key)
        (.close (.socket socket-channel)))
      (.write socket-channel *buffer*))))

(defn react [selector server-socket]
  (while true
    (when (> (.select selector) 0)
      (let [selected-keys (.selectedKeys selector)]
        (doseq [k selected-keys]
          (condp state= k
            SelectionKey/OP_ACCEPT
            (accept-connection server-socket selector)
            SelectionKey/OP_READ
            (read-socket k)))
        (.clear selected-keys)))))

(defn run []
  (apply react (setup 2323)))
Published on

Blogging like a Ruby Hacker

Kind of a weird thing to say for someone who does not program Ruby, don’t you think?

I have been wanting to move away from Posterous for quite a while now. I’ve searched for solutions in languages I know and even spent some time writing something in Clojure.

All in all, I wasn’t getting anywhere, so I just said to myself that I wanted to have my blog in a static site generator today.

I chose Jekyll because it’s the first and most popular one I knew. It’s also used by Github and is named after “The Strange Case of Dr Jekyll and Mr Hyde”. Only, it’s in Ruby.

It turns out Ruby syntax is quite easy to guess right for a Python dev. Before I could get started, I had to hack a Posterous migrator to support my old links, tags and images.

So, I hope you like my new old theme and that you don’t find to much broken stuff.

I don’t have comments for the moment, so you’ll have to email me when you have problems. I do plan to add search from Tapir soon.