Skip to content

Instantly share code, notes, and snippets.

@bartread
Created February 11, 2017 15:09
Show Gist options
  • Save bartread/b94784a3bc6579a7100d283c3f02cb2b to your computer and use it in GitHub Desktop.
Save bartread/b94784a3bc6579a7100d283c3f02cb2b to your computer and use it in GitHub Desktop.
Asynchronously loading music and sound effects to play via Web Audio API for arcade.ly games
function _initialiseSoundEffects() {
_loadSounds(soundConfiguration.sounds, true);
_loadSounds(soundConfiguration.music, false);
}
function _loadSounds(sounds, areSfx) {
for (var soundIndex = 0, soundCount = sounds.length; soundIndex < soundCount; ++soundIndex) {
var sound = sounds[soundIndex];
if (areSfx) {
sound.elementIndex = 0;
}
service[sound.id] = sound;
sound.gain = context.createGain();
sound.gain.gain.value = sound.volume * soundConfiguration.sfxMasterVolume;
sound.gain.connect(context.destination);
_loadSound(sound);
}
}
function _loadSound(sound) {
var request = new XMLHttpRequest();
request.open(
'GET',
os.isPhone && sound.srcLowQuality
? sound.srcLowQuality
: sound.src,
true);
request.responseType = 'arraybuffer';
request.onload = function () {
context.decodeAudioData(request.response, function(buffer) {
sound.buffer = buffer;
});
};
request.send();
}
/*
This code is licensed under the terms of the MIT License as described
in LICENSE.txt.
Copyright (c) 2015 - 2017 Bart Read, arcade.ly (https://arcade.ly),
and bartread.com Ltd (http://www.bartread.com/)
The soundConfiguration service is a per-game service, implemented by
games at https://arcade.ly, that provides configuration for sound
effects and music to the sfx service, thus allowing them to be played.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment