WAM - Web Audio Manager
WAM is a small, flexible and dependency free library that helps you manage sounds on your website trough Web Audio Api!
Live Demo
https://lavolpecheprogramma.github.io/web-audio-manager
Basic config
To play a single track in loop on your site:
//create webaudio contextconst wam = ;// create an AudioTrack and start to loadconst track = wam;// connect the track to speakerstrackgain;// play the track in looptrack;...// you can pause the tracktrack// or fadeout in a given timetrack;
Advanced usage
AudioGroup
To switch between tracks you can create an AudioGroup
, which provides a fade transition between tracks.
group;
It is useful if you have a set of background tracks that have to play once at time and another set of sounds (like FX) that you want to play indipendently.
// create a manager, which will bind to a new [AudioContext](https://developer.mozilla.org/en-US/docs/Web/API/AudioContext)const wam = ;// create an AudioGroupconst backgroundGroup = wam;// add tracks to it;;//connect group to speakersgroupgain;// play first track by idgroup;// for example we have a button to change the trackbutton;
Analyzer
Often you want some action to happen in reaction to audio, you can use AnalyzerNode
, which provides you with utilities for doing so.
Beat Detection
Here is code for basic beat detection:
First you initialize an AnalyzerNode
, connect it to a GainNode
and call setupBeatDetection
const analyzer = wamanalyzer;const analyzerSettings =holdTime: 30 //num of frames to hold a beatdecay: 098beatMin: 05 //a volume less than this is no beat;analyzer
In this example you can see a basic configuration, but you can play around with the settings to obtain detection of different patterns.
Then you can do
analyzerconst framesSinceLastBeat = analyzer
This will provide you the number of frames since the last beat peak was detected. This way you can set frames on your animations, or simply check when the beat starts and fire them.
You have to call analyzer.update()
before analyzer.detectBeat()
if you need the most recent info about the audio being analyzed.
Using the above configuration we can now do:
//create an AudioTrack and start to loadconst track = wam;// connect the track to analyzertrackgain;// example function of beat detection{// every frame call this functionwindow;// update track dataanalyzer;// return the number of frame from last detectionvar isBeatDetected = analyzer;//if is the first frame after detectionifisBeatDetected < 1console;}// start to analyze audio that come to the analyzer;
Analyze specific frequency band
If you want to customize further the analyzer and watch for specific frequencies, you can do so by using
analyzer.registerFreqBand(id, startFreq, endFreq)
Calling getFreqBand(id)
will provide you with a value between 0 and 1 which is the volume of those frequency bands.
Calling getAllFreqBand()
instead will provide you with an object where each key is the band id you choose when setting it up, and the value is the frequency band volume, always between 0 and 1.
// setup analyzeranalyzer;analyzer;// example function of beat detection{...// update track dataanalyzer;const kickLevel = analyzer;// scale an element according to kick leveldivstyletransform = 'scale('+ kickLevel +')';}
WebAudioManager
Constructor
Return the instance of WebAudioManager. Accept one parameter that is the maxVolume of the master gain so you can easily control the volume of all your sounds.
const wam = ;
or
const wam = 08;
wam.ctx
Return the AudioCtx.
It is important because you have to pass it during creation of other nodes.
// create an analyzerconst analyzer = wam;
or
//create an AudioTrack and start to loadconst track = wam;
wam.gain
Return the gainNode instance attached to webaudio manager, it is automatically attached to speakers. It is useful to attach other nodes to speakers or if you want to change the volume of all you sounds;
analyzer;
or
wamgain;
onChangePageVisibility(pageIsVisible)
This method allow you to automatically toggle volume on page visibility
var hidden visibilityChange;if typeof documenthidden !== "undefined" // Opera 12.10 and Firefox 18 and later supporthidden = "hidden";visibilityChange = "visibilitychange";else if typeof documentmsHidden !== "undefined"hidden = "msHidden";visibilityChange = "msvisibilitychange";else if typeof documentwebkitHidden !== "undefined"hidden = "webkitHidden";visibilityChange = "webkitvisibilitychange";{wam;//.... other things to do on page visibility changes}// Warn if the browser doesn't support addEventListener or the Page Visibility APIif typeof documentaddEventListener === "undefined" || typeof documenthidden === "undefined"console;else// Handle page visibility changedocument;
AudioTrack
Constructor
Return the instance of AudioTrack. Accept two parameters:
- An object that define the information of track:
const dataTrack =id: 'sample' // required only when a track is added to an AudioGroupurl: './test.mp3' // path to audio filepreload: true // (optional) load on creation of AudioTrack;
- The webaudio context
So to create a new AudioTrack you can do something like this:
//create an AudioTrack and start to loadconst track = wam;
track.gain
Return the gainNode instance attached to the instance. It is useful to attach the track to a node or to change the volume.
analyzer;
or
trackgain;
track.load()
Start to load the audio file. Return a promise.
track
play(loop, startVolume)
Play the audio file when loaded is completed. The startVolume is useful if you want to play the sound, and then do a fade in of audio. Return a promise.
// play the track not in looptrack
or
// play the track in looptrack
or
// play the track in loop, and with a start volume of 0;track
stop(delay)
Stop the audio file. You can pass a delay to stop the track after n seconds (default is 0) Return a promise.
track
or
//stop track after 1 secondtrack
pause(delay)
Pause the audio file, you can use it if you want to play again the track from the last state. You can pass a delay to pause the track after n seconds (default is 0). Return a promise.
track
or
//pause track after 1 secondtrack
fade(type, time, loop)
It allow you to create an audio fade (in/out) with a specified time (default is 0.5s). If you make a fadeIn you can control if the track that fade in have to play in loop or not.
track
or
// fade out of 1 secondtrack
or
track
remove()
This function stop the track if it's playing, disconnect and remove the gain attached to the track.
track;
AudioGroup
Constructor
Return the instance of AudioTrack. Audio context required.
//create an AudioGroupconst group = wam;
group.gain
Return the gainNode instance attached to the instance. It is useful to attach the group to a node or to change the volume.
analyzer;
or
groupgain;
group.addTrack(trackData)
Add an instance of track by id and connect the track gain to the AudioGroup gain.
group
group.getTrack(id)
Return an instance of track by id.
group
group.removeTrack(id)
Remove single instance of track by id.
group;
group.setCurrentTrack(id, fade, loop)
Set the new track to play by id. Optionally you can set the fade in of the track and if it have to play in loop or not. If another track in this group is playing, it will fade out automatically with the same duration fade you have passed like param.
// play the track without transitiongroup;
or
// play the track with a fade transition of 2 secondsgroup;
or
// play the track in loop with a fade transition of 2 secondsgroup;
group.remove()
Remove all instance of tracks instanciated in this group.
group;
GainNode
Constructor
Return the instance of GainNode.
gainNode = ;
gainNode.connectNode(nodeTo)
gainNode
gainNode.disconnectNode()
gainNode
gainNode.connectBuffer(buffer, loop)
gainNode
gainNode.disconnectBuffer()
gainNode
gainNode.setVolume(volume, fadeDuration)
gainNode
gainNode.play(atTime){
gainNode
gainNode.pause(delay){
gainNode
gainNode.stop(delay){
gainNode
gainNode.remove(){
gainNode
AnalyzerNode
Constructor
const analyzer = wam;
connectNode(nodeTo)
analyzer;
disconnectNode()
analyzer
setupBeatDetection(opts)
analyzer
detectBeat()
analyzer
registerBand(name, start, end)
analyzer;
getFreqBand(id)
const currentKickLevel = analyzer
getAllFreqBand()
const allRegistererBandLevel = analyzer;
update()
analyzer
License
MIT.