Last active
March 30, 2020 22:29
-
-
Save bobbicodes/579414ee10e62817bfbbaeafc18f549c to your computer and use it in GitHub Desktop.
Play audio files one after the other. Shows how to use promises
This file contains hidden or 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
(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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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