Skip to content

Instantly share code, notes, and snippets.

@bartread
Last active June 4, 2016 10:50
Show Gist options
  • Save bartread/af5043df694e47bbfd81fae0cef61d0b to your computer and use it in GitHub Desktop.
Save bartread/af5043df694e47bbfd81fae0cef61d0b to your computer and use it in GitHub Desktop.
Playing sound effects and music in games at https://arcade.ly - notably Star Citadel, which is available at http://starcas.tl
MIT License
Copyright (c) 2015, 2016 Bart Read, arcade.ly (https://arcade.ly), and
bartread.com Ltd (http://www.bartread.com/)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in the
Software without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/*
This code is licensed under the terms of the MIT License as described
in LICENSE.txt.
Copyright (c) 2015, 2016 Bart Read, arcade.ly (https://arcade.ly),
and bartread.com Ltd (http://www.bartread.com/)
The pinjector is loosely based on a limited subset of the Angular 1.x
module API and injector that is used for service registration and
dependency injection by games at http://arcade.ly. It exists because
the first game was initially implemented using AngularJS until Bart
experience a moment of clarity in which he realised this was an
insane thing to use Angular for but couldn't be bothered with the
faff of switching everything over to a different module system and
API.
*/
'use strict'; // jshint ignore:line
var pinjector = {};
(function () {
pinjector.module = module;
var modules = {};
function module(name) {
var controllers = {};
var factories = {};
var module = modules[name];
if (!module) {
module = {
controller: controller,
factory: factory,
run: run,
getController: getController
};
modules[name] = module;
}
return module;
function controller(constructorName, params) {
controllers[constructorName] = {
name: constructorName,
params: params,
controller: params[params.length -1]
};
}
function getController(controllerName) {
return controllers[controllerName].controller;
}
function factory(constructorName, params) {
factories[constructorName] = {
name: constructorName,
params: params,
constructor: params[params.length -1]
};
}
function run(controllerName) {
resolve();
var controllerDefinition = controllers[controllerName];//module.getController(controllerName);
if (!controllerDefinition) {
throw 'Specified controller "' + controllerName + '" is not registered. Unable to run.';
}
var main = controllerDefinition.controller.main;
if (!main) {
throw 'Controller "' + controllerName + '" doesn\'t export a main function. Unable to run.';
}
main();
}
function resolve() {
for (var propName in factories) {
if (!factories.hasOwnProperty(propName)) {
continue;
}
resolveFactoryName(propName);
}
resolveControllerDependencies();
}
function resolveControllerDependencies() {
for (var propName in controllers) {
if (!controllers.hasOwnProperty(propName)) {
continue;
}
var controllerDefinition = controllers[propName];
resolveFactoryDefinition(controllerDefinition);
}
}
function resolveFactoryName(factoryName) {
var definition = factories[factoryName];
if (definition) {
return resolveFactoryDefinition(definition);
}
return null;
}
function resolveFactoryDefinition(factoryDefinition) {
if (factoryDefinition.factory) {
return factoryDefinition.factory;
}
var dependencies = [];
var size = factoryDefinition.params.length - 1;
for (var index = 0; index < size; ++index) {
var name = factoryDefinition.params[index];
var dependency = resolveFactoryName(name);
if (dependency) {
dependencies.push(dependency);
} else {
throw 'Unable to resolve dependency "' +
name +
'" for factory "' +
factoryDefinition.name +
'".';
}
}
var constructor = factoryDefinition.params[size];
var factory = constructor.apply(constructor, dependencies);
factoryDefinition.factory = factory;
return factory;
}
}
}());
/*
This code is licensed under the terms of the MIT License as described
in LICENSE.txt.
Copyright (c) 2015, 2016 Bart Read, arcade.ly (https://arcade.ly),
and bartread.com Ltd (http://www.bartread.com/)
The os service exposes operating system and browser information to
games at http://arcade.ly via a simple interface in order to allow
them to make necessary behavioural modifications to compensate for
differences in performance and behaviour in different browsers.
*/
f(function () {
'use strict';
pinjector
.module('starCastle')
.factory(
'os',
[
os
]);
function os() {
var service = {
isDesktop: true,
isIos: false,
isAndroid: false,
isWindowsPhone: false,
isTouch: false,
isPhone: false,
isTablet: false,
isSafari: false,
isChrome: true,
isFirefox: false,
isIe: false,
isEdge: false
};
detect();
return service;
function detect() {
var userAgent = navigator.userAgent,
platform = navigator.platform;
// Checking this first is important because on Windows
// Phone 8.1 IE11 spoofs the user agent to include iOS
// and Android. I imagine the same is also true for Edge
// on Windows 10 Mobile, though I don't have a device
// to test with. Shouldn't make any difference anyway
// if not.
detectWindowsPhone(userAgent);
if (userAgent.isWindowsPhone) {
detectDesktopOrWindowsPhoneBrowser(userAgent);
} else {
if (userAgent && userAgent.indexOf('iPhone') >= 0
|| platform && platform.indexOf('iPhone') >= 0) {
service = {
isDesktop: false,
isIos: true,
isAndroid: false,
isWindowsPhone: false,
isTouch: true,
isPhone: true,
isTablet: false,
isSafari: true,
isChrome: false,
isFirefox: false,
isIe: false,
isEdge: false
};
} else if (userAgent && userAgent.indexOf('iPad') >= 0
|| platform && platform.indexOf('iPad') >= 0) {
service = {
isDesktop: false,
isIos: true,
isAndroid: false,
isWindowsPhone: false,
isTouch: true,
isPhone: false,
isTablet: true,
isSafari: true,
isChrome: false,
isFirefox: false,
isIe: false,
isEdge: false
};
} else if (userAgent && userAgent.indexOf('Android') >= 0
|| platform && platform.indexOf('Android') >= 0) {
service = {
isDesktop: false,
isIos: false,
isAndroid: true,
isWindowsPhone: false,
isTouch: true,
isPhone: true,
isTablet: false,
isSafari: false,
isChrome: true, // This might not be true
isFirefox: false, // Might be true
isIe: false,
isEdge: false
};
// TODO: Android tablet detection
} else {
detectDesktopOrWindowsPhoneBrowser(userAgent);
}
}
if (service.isIos) {
service.iOsVersion = getIOsVersion(userAgent);
checkAndSetOldIOs();
}
}
function detectWindowsPhone(userAgent) {
if (!userAgent) {
return;
}
userAgent = userAgent.toLowerCase();
if (userAgent.indexOf('windows phone') >= 0) {
service.isWindowsPhone = true;
service.isDesktop = false;
service.isPhone = true;
service.isTouch = true;
}
}
function detectDesktopOrWindowsPhoneBrowser(userAgent) {
if (!userAgent) {
return;
}
userAgent = userAgent.toLowerCase();
if (userAgent.indexOf('edge') >= 0) {
service.isChrome = false;
service.isEdge = true;
} else if (userAgent.indexOf('msie') >= 0 || userAgent.indexOf('trident') >= 0) {
service.isChrome = false;
service.isIe = true;
} else if (userAgent.indexOf('chrome') >= 0) {
service.isChrome = true; // This is a no-op
} else if (userAgent.indexOf('firefox') >= 0) {
service.isChrome = false;
service.isFirefox = true;
} else if (userAgent.indexOf('safari') >= 0) {
service.isChrome = false;
service.isSafari = true;
}
}
function getIOsVersion(source) {
var match = source.match(/OS (\d+)_(\d+)_?(\d+)?/);
if (match) {
return {
major: parseInt(match[1], 10),
minor: parseInt(match[2], 10),
patch: parseInt(match[3] || 0, 10)
};
}
return undefined;
}
function checkAndSetOldIOs() {
if (service.isIos) {
var version = service.iOsVersion;
if ((version && version.major < 9)
|| (version.major === 9 && version.minor < 3)) {
service.isOldIOs = true;
}
}
service.isOldIOs = false;
}
}
}());
/*
This code is licensed under the terms of the MIT License as described
in LICENSE.txt.
Copyright (c) 2015, 2016 Bart Read, arcade.ly (https://arcade.ly),
and bartread.com Ltd (http://www.bartread.com/)
The sfx service is used by games at https://arcade.ly to play sound
effects and music in web pages. It preferentially uses the Web Audio
API but, where this is not available, will fall back to use HTML5
<audio> elements.
*/
(function () {
'use strict';
pinjector
.module('starCastle')
.factory(
'sfx',
[
'soundConfiguration',
'arcadeSettings',
'os',
sfx
]);
function sfx(soundConfiguration, arcadeSettings, os) {
var sfxService,
context = getWebAudioContext(),
effectsThatWerePlaying,
areSfxEnabledFlag = true,
currentMusic,
isMusicEnabledFlag = true;
initAudioEnabledSettings();
sfxService = context
? createWebAudioService(context)
: createAudioElementService();
return sfxService;
function initAudioEnabledSettings() {
var enabled = arcadeSettings.get('arcade.musicEnabled');
isMusicEnabledFlag = enabled === undefined || enabled === null || enabled === 'true';
enabled = arcadeSettings.get('arcade.sfxEnabled');
areSfxEnabledFlag = enabled === undefined || enabled === null || enabled === 'true';
}
function getWebAudioContext() {
try {
var ctor = window.AudioContext || window.webkitAudioContext;
return ctor ? new ctor() : null;
} catch (e) {
return null;
}
}
function _unlockAudio() {
_playInitialSound();
// Fix for iOS audio distortion
if (context.sampleRate === 48000) {
context = getWebAudioContext();
_playInitialSound();
}
}
function _playInitialSound() {
var buffer = context.createBuffer(1, 1, 22050);
var source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
if (!source.start) {
source.start = source.noteOn;
}
source.start();
}
function createWebAudioService(context) {
var service = {
play: _play,
playByName: _playByName,
stop: _stop,
stopByName: _stopByName,
toggleEffects: _toggleEffects,
areEffectsEnabled: _areEffectsEnabled,
playMusic: _playMusic,
playMusicByName: _playMusicByName,
stopMusic: _stopMusic,
toggleMusic: _toggleMusic,
isMusicReady: _isMusicReady,
isMusicReadyByName: _isMusicReadyByName,
isMusicEnabled: _isMusicEnabled,
pause: _pause,
resume: _resume,
unlockAudio: _unlockAudio
};
var allSources = [],
musicTimeout = null;
_initialiseSoundEffects();
return service;
function _play(effect) {
if (!areSfxEnabledFlag || !effect) {
return;
}
var buffer = effect.buffer;
if (!buffer) {
return;
}
var source = context.createBufferSource();
source.buffer = buffer;
effect.mediaSource = source;
source.connect(effect.gain);
if (!source.start) {
source.start = source.noteOn;
}
source.start(0);
}
function _playByName(name) {
_play(service[name]);
}
function _stop(effect) {
if (!effect) {
return;
}
var mediaSource = effect.mediaSource;
if (!mediaSource) {
return;
}
mediaSource.stop();
effect.mediaSource = null;
}
function _stopByName(name) {
_stop(service[name]);
}
function _toggleEffects() {
if (areSfxEnabledFlag) {
areSfxEnabledFlag = false;
effectsThatWerePlaying = null;
for (var index = 0, size = allSources.length; index < size; ++index) {
var effect = allSources[index];
}
} else {
areSfxEnabledFlag = true;
}
arcadeSettings.set('arcade.sfxEnabled', areSfxEnabledFlag);
}
function _areEffectsEnabled() {
return areSfxEnabledFlag;
}
function _playMusic(music) {
if (musicTimeout !== null) {
window.clearTimeout(musicTimeout);
musicTimeout = null;
}
if (currentMusic === music && currentMusic.mediaSource) {
return;
}
_stopMusic();
currentMusic = music;
if (isMusicEnabledFlag && currentMusic) {
var buffer = currentMusic.buffer;
if (!buffer) {
musicTimeout = window.setTimeout(
function () { _playMusic(music); },
2000);
return;
}
var source = context.createBufferSource();
source.buffer = buffer;
source.loop = true;
music.mediaSource = source;
source.connect(music.gain);
if (!source.start) {
source.start = source.noteOn;
}
source.start(0);
}
}
function _playMusicByName(name) {
_playMusic(service[name]);
}
function _isMusicReady(music) {
return music && music.buffer;
}
function _isMusicReadyByName(name) {
return _isMusicReady(service[name]);
}
function _isMusicEnabled() {
return isMusicEnabledFlag;
}
function _stopMusic() {
if (currentMusic) {
if (currentMusic.mediaSource) {
currentMusic.mediaSource.stop();
currentMusic.mediaSource = null;
}
currentMusic = null;
}
}
function _toggleMusic() {
if (isMusicEnabledFlag) {
_pauseMusic();
isMusicEnabledFlag = false;
} else {
isMusicEnabledFlag = true;
_resumeMusic();
}
arcadeSettings.set('arcade.musicEnabled', isMusicEnabledFlag);
}
function _pauseMusic() {
if (currentMusic && currentMusic.mediaSource) {
currentMusic.mediaSource.stop();
currentMusic.mediaSource = null;
}
}
function _pause() {
if (context.state === 'running') {
context.suspend();
}
}
function _resumeMusic() {
if (isMusicEnabledFlag && currentMusic) {
_playMusic(currentMusic);
}
}
function _resume() {
if (context.state === 'suspended') {
context.resume();
}
}
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();
}
}
function createAudioElementService() {
var service = {
play: play,
playByName: playByName,
stop: stop,
stopByName: stopByName,
toggleEffects: toggleEffects,
areEffectsEnabled: areEffectsEnabled,
playMusic: playMusic,
playMusicByName: playMusicByName,
stopMusic: stopMusic,
toggleMusic: toggleMusic,
isMusicReady: isMusicReady,
isMusicReadyByName: isMusicReadyByName,
isMusicEnabled: isMusicEnabled,
pause: pause,
resume: resume,
unlockAudio: _unlockAudio
};
var allEffects = [];
initialiseSoundEffects();
return service;
function play(effect) {
if (!areSfxEnabledFlag || !effect) {
return;
}
var element = effect.elements[effect.elementIndex];
if (element.readyState >= 2) {
element.currentTime = 0;
element.play();
}
effect.elementIndex = (effect.elementIndex + 1) % effect.elements.length;
}
function playByName(name) {
play(service[name]);
}
function stop(effect) {
if (!effect) {
return;
}
var elements = effect.elements;
for (var index = 0, size = elements.length; index < size; ++index) {
var element = effect.elements[index];
if (element.readyState >= 2) {
element.pause();
}
}
}
function stopByName(name) {
stop(service[name]);
}
function toggleEffects() {
if (areSfxEnabledFlag) {
areSfxEnabledFlag = false;
effectsThatWerePlaying = null;
for (var index = 0, size = allEffects.length; index < size; ++index) {
var effect = allEffects[index];
if ((!currentMusic || effect != currentMusic.element)
&& !effect.paused) {
effect.pause();
}
}
} else {
areSfxEnabledFlag = true;
}
arcadeSettings.set('arcade.sfxEnabled', areSfxEnabledFlag);
}
function areEffectsEnabled() {
return areSfxEnabledFlag;
}
function playMusic(music) {
stopMusic();
currentMusic = music;
if (isMusicEnabledFlag && currentMusic) {
var element = currentMusic.element;
if (element.readyState >= 2) {
element.currentTime = 0;
element.play();
}
}
}
function playMusicByName(name) {
playMusic(service[name]);
}
function isMusicReady(music) {
return music && music.element && music.element.readyState >= 2;
}
function isMusicReadyByName(name) {
return isMusicReady(service[name]);
}
function isMusicEnabled() {
return isMusicEnabledFlag;
}
function stopMusic() {
if (currentMusic) {
currentMusic.element.pause();
currentMusic = null;
}
}
function toggleMusic() {
if (isMusicEnabledFlag) {
pauseMusic();
isMusicEnabledFlag = false;
} else {
isMusicEnabledFlag = true;
resumeMusic();
}
arcadeSettings.set('arcade.musicEnabled', isMusicEnabledFlag);
}
function pauseMusic() {
if (currentMusic) {
currentMusic.element.pause();
}
}
function pause() {
pauseMusic();
effectsThatWerePlaying = [];
if (allEffects) {
for (var index = 0, size = allEffects.length; index < size; ++index) {
var effect = allEffects[index];
if (!effect.paused) {
effectsThatWerePlaying.push(effect);
effect.pause();
}
}
}
}
function resumeMusic() {
if (isMusicEnabledFlag && currentMusic && currentMusic.element.readyState >= 2) {
currentMusic.element.play();
}
}
function resume() {
resumeMusic();
if (effectsThatWerePlaying) {
for (var index = 0, size = effectsThatWerePlaying.length; index < size; ++index) {
effectsThatWerePlaying[index].play();
}
effectsThatWerePlaying = null;
}
}
function initialiseSoundEffects() {
var body = document.getElementsByTagName('body')[0];
var children = body.childNodes;
var repeats = soundConfiguration.elementCountForRapidRepeat;
var sounds = soundConfiguration.sounds,
audio;
for (var soundIndex = 0, soundCount = sounds.length; soundIndex < soundCount; ++soundIndex) {
var sound = sounds[soundIndex];
var elements = [];
sound.elements = elements;
sound.elementIndex = 0;
service[sound.id] = sound;
for (var elementIndex = 0, elementCount = sound.rapidRepeat ? repeats : 1; elementIndex < elementCount; ++elementIndex) {
audio = document.createElement('audio');
audio.id = sound.id + elementIndex;
audio.src = sound.src;
if (sound.volume) {
audio.volume = sound.volume;
}
audio.preload = 'auto';
body.appendChild(audio);
allEffects.push(audio);
elements.push(audio);
}
}
var music = soundConfiguration.music;
for (var musicIndex = 0, musicCount = music.length; musicIndex < musicCount; ++musicIndex) {
var track = music[musicIndex];
service[track.id] = track;
audio = document.createElement('audio');
audio.id = track.id;
audio.src = track.src;
if (track.volume) {
audio.volume = track.volume;
}
audio.preload = 'auto';
if (track.autoplay) {
audio.setAttribute('autoplay', '');
}
audio.setAttribute('loop', '');
body.appendChild(audio);
allEffects.push(audio);
track.element = audio;
}
}
}
}
}());
/*
This code is licensed under the terms of the MIT License as described
in LICENSE.txt.
Copyright (c) 2015, 2016 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.
*/
(function () {
'use strict';
pinjector
.module('starCastle')
.factory(
'soundConfiguration',
[
soundConfiguration
]);
function soundConfiguration() {
var config = {
elementCountForRapidRepeat: 6,
sfxMasterVolume: 0.4,
musicMasterVolume: 0.6,
sounds: [{
id: 'playerShot',
src: './content/sounds/PlayerShot.mp3',
volume: 0.3,
rapidRepeat: true
}, {
id: 'playerMaterialise',
src: './content/sounds/PlayerMaterialise.mp3',
volume: 1.0,
rapidRepeat: true
}, {
id: 'shieldImpact',
src: './content/sounds/ShieldImpact.mp3',
volume: 1.0,
rapidRepeat: true
}, {
id: 'shieldExplode',
src: './content/sounds/ShieldExplode.mp3',
volume: 0.5,
rapidRepeat: true
}, {
id: 'playerThrust',
src: './content/sounds/PlayerThrust.mp3',
volume: 0.4
}, {
id: 'cannonThrust',
src: './content/sounds/CannonThrust.mp3',
volume: 0.1
}, {
id: 'cannonFire',
src: './content/sounds/CannonFire.mp3',
volume: 1.0
}, {
id: 'lowBoom',
src: './content/sounds/LowBoom.mp3',
volume: 1.0
}, {
id: 'smallBoom',
src: './content/sounds/SmallBoom.mp3',
volume: 1.0,
rapidRepeat: true
}, {
id: 'cannonLock',
src: './content/sounds/CannonLock.mp3',
volume: 0.4
}, {
id: 'cannonMaterialise',
src: './content/sounds/CannonMaterialise.mp3',
volume: 1.0,
rapidRepeat: true
}, {
id: 'mineRelease',
src: './content/sounds/MineRelease.mp3',
volume: 1.0,
rapidRepeat: true
}, {
id: 'mineCapture',
src: './content/sounds/MineCapture.mp3',
volume: 1.0,
rapidRepeat: true
}, {
id: 'alienScream',
src: './content/sounds/AlienScream.mp3',
volume: 1.0,
rapidRepeat: true
}, {
id: 'buttonClick',
src: './content/sounds/50635__cbakos__newwallswitchon.mp3',
volume: 1.0,
rapidRepeat: true
}],
music: [{
id: 'titleMusic',
src: './content/music/179_full_arrested-for-driving-while-mad_0159.mp3',
srcLowQuality: './content/music/179_full_arrested-for-driving-while-mad_0159_lowquality.mp3',
volume: 1.0,
autoplay: true
}, {
id: 'levelMusic',
src: './content/music/179_full_a-naked-gun-bank-assault_0100.mp3',
srcLowQuality: './content/music/179_full_a-naked-gun-bank-assault_0100_lowquality.mp3',
volume: 1.0
}, {
id: 'gameOverMusic',
src: './content/music/156_full_good-ol-western_0123.mp3',
srcLowQuality: './content/music/156_full_good-ol-western_0123_lowquality.mp3',
volume: 1.0
}]
};
return config;
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment