Web Audio API spec is a great way of professional audio playing and mixing in the modern browser. However, it's too complex and versatile for some simple one-off tasks such as "load an audio sample into memory and just play it when necessary". That's why Samples.js has come true. It's a really simple and tiny (less than 1K minified) library that exposes just 5 methods to manipulate your samples from JS code in a really easy and fun way.
The library exposes the following calls:
samples.load(key, urlOrFile[, callback])
- load an audio sample from a URL (absolute or relative) via AJAX or from a File object (obtained from<input type=file>
, for example), save it in the memory underkey
key and call the optional callback function if present. For the convenience, the loaded sample key is passed as a single parameter to the callback.samples.unload(key)
- completely delete the sample stored underkey
from the memory.samples.start(key)
- start playing the sample stored underkey
.samples.stop(key)
- stop playing the sample stored underkey
.samples.setLooping(key, value)
- turn the sample looping on/off (value
can betrue
orfalse
). Ifnull
is passed as thekey
, the looping is set/unset for all loaded samples at once.
The following example will load some ding.wav
file via AJAX and play it as soon as it's ready.
samples.load('bell', 'samples/ding.wav', function(key){
samples.start('bell') //alternatively, we could just pass key parameter here
})
For the best showcase of what this library can do, see the numLaunchpad online drum/beat machine app that uses Samples.js as the only sound library.
The library is compatible with all browsers that follow current standard Web Audio API and XHR2 specifications and also implement FileReader and ArrayBuffer interfaces. So recent Chrome, Firefox and Opera versions should be just fine. As for performance, some lags have been noticed on Firefox for Android but that's the drawback of native Web Audio API performance there.