Skip to content

Instantly share code, notes, and snippets.

@msgodf
Created March 1, 2014 20:26
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msgodf/9296652 to your computer and use it in GitHub Desktop.
Save msgodf/9296652 to your computer and use it in GitHub Desktop.
A Clojurescript port of the first of the Web Audio API examples from HTML5 Rocks (http://www.html5rocks.com/en/tutorials/webaudio/intro/)
(ns cljsaudio.core
(:require [goog.net.XhrIo]
[cljs.core.async :as async :refer [<! >! chan close!]])
(:require-macros [cljs.core.async.macros :refer [go]]))
(defn decode-audio-data
[context data]
(let [ch (chan)]
(.decodeAudioData context
data
(fn [buffer]
(go (>! ch buffer)
(close! ch))))
ch))
(defn get-audio [url]
(let [ch (chan)]
(doto (goog.net.XhrIo.)
(.setResponseType "arraybuffer")
(.addEventListener goog.net.EventType.COMPLETE
(fn [event]
(let [res (-> event .-target .getResponse)]
(go (>! ch res)
(close! ch)))))
(.send url "GET"))
ch))
(defn play-audio
[url]
(go
(let [response (<! (get-audio url))
AudioContext (or (.-AudioContext js/window)
(.-webkitAudioContext js/window))
context (AudioContext.)
buffer (<! (decode-audio-data context response))
source (doto (.createBufferSource context)
(aset "buffer" buffer))]
(.connect source (.-destination context))
(.start source 0))))
(play-audio "../techno.wav")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment