Created
March 1, 2014 20:26
-
-
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/)
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 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