To play samples with the webaudi API you first need a sample source, a binary sound file in a format your browser is able to decode. The sample, in the format of an ArrayBuffer, must then be decoded by audioContext.decodeAudioData.
The resulting AudioBuffer is played by an AudioBufferSourceNode. When play has finished the node dispatches the 'ended' event, a listener function does cleanup; stops the node, and disconnects it from the output. The ArrayBuffer that is passed to the decodeAudioData method is processed and then erased. When you want to keep the buffer make a copy using buffer.slice() as in this example.
The AudioBufferSourceNode has a 'loop' property, when set to true, the sample is replayed indefinitely. The node has two properties to influence the frequency of the sample; detune and playbackRate. Detune has influence on the playbackrate as well, but uses a value in cents. 100 cents is halve a tone distance; the difference in frequency between 2 consecutive keys on a keyboard. The playbackrate is 1 by default, the native sampling rate of the sound. When the playbackrate is doubled, then the playback frequency or tone also doubles in hight. The native tone of the piano tone sample is C4 or 261.63Hz. When it should sound at A4 or 440Hz, then use this formula: playbackRate = 440 / fSample = 440 / 261.63 = 1.68. The 'Grand Piano' demo uses the same sample foar all of it's tones, but the playbackRate for each tone differs.
When you want to use short audio samples in your project, eg a Midi player, you need an easy way to load and save the samples. Instead of having to load a lot of samples first at the start of your app, it's much easier to put all the samples in a library file, along with information about its type, load the single file and retrieve your samples.
I made a software module that takes care of this, you can download the .js file and link it to your project. I also made an app that makes it easy to compile a library file. You can find it here. There two sample libraries available for download. One with three samples of a Yamaha grand piano, and one with 13 samples of percussion instruments. I took the samples from this website and adjusted them a bit with Audacity.
The module has 4 functions:
Make a new library, add a sample file, then save the library.
Read samples back from the library
The processSample function decodes the raw sample data, and replaces it by an AudioBuffer.