Skip to content

Instantly share code, notes, and snippets.

@jakelodwick
Created December 21, 2015 22:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakelodwick/ee22d8a19e53ed9d65ed to your computer and use it in GitHub Desktop.
Save jakelodwick/ee22d8a19e53ed9d65ed to your computer and use it in GitHub Desktop.
load multiple files via XHR, then run a callback
loadSamples: (urls, callback) ->
loaded = []
requests = []
decode = (_raw) =>
@audio.decodeAudioData _raw, (sample) ->
loaded.push sample
callback(loaded) if loaded.length is urls.length
for url, i in urls
requests[i] = new XMLHttpRequest()
requests[i].open 'GET', url, true
requests[i].responseType = 'arraybuffer'
requests[i].onload = ->
decode this.response
requests[i].send()
@jakelodwick
Copy link
Author

And if you want to keep track of them (by using an object instead of an array),

    # define the loader function
    loadSamples = (requested, callback) ->

      loaded = {}
      XHRs = {}
      audio = @audio

      decode = (_name, _raw) =>
        audio.decodeAudioData _raw, (sample) =>
          loaded[_name] = sample
          callback(loaded) if _.size(loaded) is _.size(requested)

      for name, url of requested
        XHRs[name] = new XMLHttpRequest()
        XHRs[name]._name = name #meh
        XHRs[name].open 'GET', url, true
        XHRs[name].responseType = 'arraybuffer'
        XHRs[name].onload = ->
          decode this._name, this.response
        XHRs[name].send()

      # define the samples
      samples =
        vox: "/audio/120_1Bar_VoxSample4ChokeTest.wav",
        tick: "/audio/CLK_LOGICA.wav",
        tock: "/audio/CLK_LOGICB.wav"

      # call the loadSamples function & pass results into a callback function
      loadSamples samples, @makeSomethingThatUsesAudio

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