Abstracting audio
First let's create a very simple library to abstract interactions between our framework and the sound implementation we chose. The following code represents a "contract" that all our implementations will have to respect:
// a sound object sound = function(){ // Preloads the sound this.preload = function(url){ // TODO: implement }; // Returns true if the sound is preloaded this.isPreloaded = function(){ // TODO: implement } // Starts to play the sound. If loop is true the // sound will repeat until stopped this.play = function(loop){ // TODO: implement }; // Stops the sound this.stop = function(){ // TODO: implement }; };
For the Web Audio API implementation, we will add more capabilities to our object, but this is the basic functionality you might expect for any audio library.
Using our small library
To use a sound in our game we will simply link the corresponding implementation to our HTML file:
<script type="text/javascript...