An simple and flexible audio buffer loader for browser:
var ac = new AudioContext()
var load = require('audio-loader')
// load one file
load(ac, 'http://example.net/audio/file.mp3').then(function (buffer) {
console.log(buffer) // => <AudioBuffer>
})
// load a collection of files
load(ac, { snare: 'samples/snare.wav', kick: 'samples/kick.wav' },
{ from: 'http://example.net/'} ).then(audio) {
console.log(audio) // => { snare: <AudioBuffer>, kick: <AudioBuffer> }
})
- Load single audio files or collection of them (either using arrays or data objects)
- Load base64 encoded audio strings
- Compatible with midi.js pre-rendered soundfonts packages
## Install
Via npm: npm i --save audio-loader
or grab the browser ready file (4kb) which exports loadAudio
as window global.
Param | Type | Description |
---|---|---|
ac | AudioContext |
the audio context |
source | Object |
the object to be loaded |
options | Object |
(Optional) the load options for that object |
Possible option keys:
- from {Function|String}: a function or string to convert from file names to urls.
If is a string it will be prefixed to the name:
load(ac, 'snare.mp3', { from: 'http://audio.net/samples/' })
If it's a function it receives the file name and should return the url as string. - only {Array} - when loading objects, if provided, only the given keys
will be included in the decoded object:
load(ac, 'piano.json', { only: ['C2', 'D2'] })
You can load individual or collection of files:
var ac = new AudioContext()
load(ac, 'http://path/to/file.mp3').then(function (buffer) {
// buffer is an AudioBuffer
play(buffer)
})
// apply a prefix using options.from
load(ac, ['snare.mp3', 'kick.mp3'], { from: 'http://server.com/audio/'}).then(function (buffers) {
// buffers is an array of AudioBuffers
play(buffers[0])
})
// the options.from can be a function
function toUrl (name) { return 'http://server.com/samples' + name + '?key=secret' }
load(ac, { snare: 'snare.mp3', kick: 'kick.mp3' }, { from: toUrl }).then(function (buffers) {
// buffers is a hash of names to AudioBuffers
play(buffers['snare'])
})
audio-loader
will detect if some of the values of an object is an audio file name and try to fetch it:
var inst = { name: 'piano', gain: 0.2, audio: 'samples/piano.mp3' }
load(ac, inst).then(function (piano) {
console.log(piano.name) // => 'piano' (it's not an audio file)
console.log(piano.gain) // => 0.2 (it's not an audio file)
console.log(piano.audio) // => <AudioBuffer> (it loaded the file)
})
You can load midi.js js soundfont files:
load(ac, 'acoustic_grand_piano-ogg.js').then(function (buffers) {
buffers['C2'] // => <AudioBuffer>
})
To run the test, clone this repo and:
npm install
npm test
To run the example:
npm i -g beefy
beefy example/example.js
MIT License