Skip to content

Instantly share code, notes, and snippets.

@gre
Last active December 25, 2015 12:19
Show Gist options
  • Save gre/6975153 to your computer and use it in GitHub Desktop.
Save gre/6975153 to your computer and use it in GitHub Desktop.
thoughts on Javascript browserify and implicit audio context
/**
* I'm trying to define a lot of Audio Micro Libs with Browserify (NPM style) and the require() mecanism
*
* Our Audio Micro Libs will require an audio context to work
* (e.g. we will need to access the sampleRate field or use some createNode methods of the web audio context)
*
* + Eventually we can use different audio context: the "main" one and/or an OfflineAudioContext
* which will be used to fastly compute some audio and returns audio buffer.
*/
// I translate that constraints by wrapping the library into a function which takes an audio context:
module.exports = function (audioContext) {
function Lib () { /*...using audioContext...;*/ }; Lib.prototype = {/**/};
return Lib;
}
// Now, on the user side, it turns out to be used like this:
var context = new require("audiocontext")(); // This is just a package which give a shim for window.AudioContext
var audiolib1 = require("audiolib1")(context);
var audiolib2 = require("audiolib2")(context);
// Quite cool right?
// Now, what happens if audiolib2 needs audiolib1 as a dependency?
//~ audiolib2 implementation:
var AudioLib1 = require("audiolib1");
module.exports = function (audioContext) {
var audioLib1 = AudioLib1(audioContext); // Create the lib1 for the current audioContext
function Lib2 () {
// ...
}
return Lib2;
}
// Maybe AudioLib1 can be memoized? (see http://underscorejs.org/#memoize)
module.exports = _.memoize(function (audioContext) {
function Lib1 () {
// ...
}
return Lib1;
});
/**
* What is your thoughts?
* Would that work, does that make sense for you?
*
* Maybe we don't have any case where a audiolib depends on another audiolib,
* but if we do, memoization sounds important for performance reason and also
* for using the same class everywhere (e.g. you want to use instanceof).
*/
@gre
Copy link
Author

gre commented Nov 25, 2013

my issue is more that I want to keep the "library instanciation" for a given AudioContext (because you can create multiple audio context).

So lib2 depends on lib1 but a lib2(ctx) must use the lib1(ctx) with the same ctx which leads me to the memoize pattern.

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