-
Notifications
You must be signed in to change notification settings - Fork 0
/
audio.cljs
62 lines (56 loc) · 2.15 KB
/
audio.cljs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
;; - Copyright 2020 - dkropfuntucht
(ns iris.audio
(:require [prospero.audio :as proaudio]
[prospero.events :as proevent]))
(def audio-system (atom {:context nil
:sounds {}}))
(defn ensure-audio-context!
[]
(if (nil? (:context@audio-system))
(let [constructor (or js/AudioContext
(.. js/window -AudioContext)
(.. js/window -webkitAudioContext))
ctx (constructor.)]
(swap! audio-system #(assoc % :context ctx))
ctx)
(:context @audio-system)))
(defn source-audio!
[track-name]
(if-let [sound (get-in @audio-system [:sounds track-name])]
sound
(let [ctx (ensure-audio-context!)
element (.getElementById js/document track-name)
source (.createMediaElementSource ctx element)
_ (.connect source (.. ctx -destination))
sound {:element element
:source source}]
(swap! audio-system #(assoc-in % [:sounds track-name] sound))
sound)))
(defn register-audio-track!
[track-name track-source opts]
(let [body (.querySelector js/document "body")
element (.getElementById js/document track-name)]
(when (nil? element)
(let [aud-elem (.createElement js/document "audio")]
(.setAttribute aud-elem "id" track-name)
(.setAttribute aud-elem "src" track-source)
(.appendChild body aud-elem)))
(source-audio! track-name)))
(defn queue-audio-track!
[track-name {:keys [::proaudio/emit-signal-on-end] :as opts}]
(let [ctx (ensure-audio-context!)
state (.. ctx -state)
_ (when (= "suspended" state) (.resume ctx))
sound (source-audio! track-name)]
(when (some? emit-signal-on-end)
(aset (:element sound) "onended"
(fn [e]
(proevent/send-signal! emit-signal-on-end track-name))))
(.play (:element sound))))
(defn stop-audio-track!
[track-name opts]
(let [ctx (ensure-audio-context!)
state (.. ctx -state)
_ (when (= "suspended" state) (.resume ctx))
sound (source-audio! track-name)]
(.pause (:element sound))))