Skip to content

Instantly share code, notes, and snippets.

@bobbicodes
Last active March 30, 2020 22:29
Show Gist options
  • Save bobbicodes/579414ee10e62817bfbbaeafc18f549c to your computer and use it in GitHub Desktop.
Save bobbicodes/579414ee10e62817bfbbaeafc18f549c to your computer and use it in GitHub Desktop.
Play audio files one after the other. Shows how to use promises
(defn play [audio]
(.play audio)
(js/Promise.
(fn [resolve reject]
(.addEventListener audio "ended" resolve))))
(let [s1 (.createElement js/document "audio")
s2 (.createElement js/document "audio")
s3 (.createElement js/document "audio")]
(set! (.-src s1) "ji.mp3")
(set! (.-src s2) "byo.mp3")
(set! (.-src s3) "chyu.mp3")
(set! (.-preload s1) "auto")
(set! (.-preload s2) "auto")
(set! (.-preload s3) "auto")
(-> (play s1)
(.then (play s2))
(.then (play s3))))
;(edited)
;10:42
;they all play simultaneously
;borkdude 10:44 AM
;@sova try (.then #(play s2))
;sova 10:44 AM
;whoa!
;10:44
;it worked
;thank you. i don't get it. could you help explain?
;borkdude 10:44 AM
;you have to pass a function, else the expression will already be evaluated
;sova 10:46 AM
;Neato
@bobbicodes
Copy link
Author

So I want to generalize this "play a sequence of mp3s" function. is there a way to (.createElement js/document "audio") and also set its source (set! (.-src name-of-audio-element) "chyu.mp3") without naming it? Or maybe just name it and conj it to a vector?

p-himik 18 hours ago
If you replace set! with some function that accepts the element as its first argument, you could use doto.

p-himik 18 hours ago
(doto (.createElement js/document "audio")
(.setAttribute "src" "chyu.mp3"))

sova 16 hours ago
wow you're a life saver thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment