From 40fd9ed9b7ef7afa243660d4ec56fd7b968a5c5c Mon Sep 17 00:00:00 2001 From: Fen Dweller Date: Mon, 7 Jan 2019 17:38:39 -0500 Subject: [PATCH] Play requests can wait for audio to load --- audio.js | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 53 insertions(+), 4 deletions(-) diff --git a/audio.js b/audio.js index 7251d07..472df05 100644 --- a/audio.js +++ b/audio.js @@ -1,6 +1,8 @@ let playing = []; let looping = {}; +let waiting = {}; + let audioContext; let gainControl; @@ -15,6 +17,16 @@ function setVolume(vol) { // play some sound function playSfx(name) { + + if (waiting[name]) { + waiting[name].push({ + type: "sfx", + name: name + }); + console.error(name + " isn't ready yet"); + return; + } + if (audioDict[name] == undefined) { console.error(name + " is not loaded yet, dingus"); return; @@ -33,6 +45,16 @@ function playSfx(name) { } function playLoop(name) { + + if (waiting[name]) { + waiting[name].push({ + type: "loop", + name: name + }); + console.error(name + " isn't ready yet"); + return; + } + if (audioDict[name] == undefined) { console.error(name + " is not loaded yet, dingus"); return; @@ -98,12 +120,20 @@ function cleanPlaying() { function loadAudio(name, flush=false) { + // are we already trying to get the audio? + + if (waiting[name]) { + return; + } + // do we already have the audio? if (audioDict[name] && !flush) { return; } + waiting[name] = []; + // is the audio already stored locally? if (!flush) { @@ -124,11 +154,25 @@ function cacheAndParse(name, data) { } function parseAudioData(name, data) { - console.log(data); audioContext.decodeAudioData(data, function(buffer) { audioDict[name] = buffer; - }, function(e){ console.log("Error with decoding audio data" + e.err);}); + + waiting[name].forEach(queued => { + if (queued.type == "sfx") { + playSfx(name); + } + + if (queued.type == "loop") { + playLoop(name); + } + + delete waiting[name]; + }) + }, function(e){ + console.log("Error with decoding audio data" + e.err); + delete waiting[name]; + }); } @@ -140,10 +184,15 @@ function loadRemoteAudio(name) { xhr.onload = (res) => { if (xhr.status == 200) cacheAndParse(name, xhr.response); - else + else { console.log("Couldn't load " + name); + delete waiting[name]; + } + } + xhr.onerror = (xhr) => { + console.log("Couldn't load " + name); } - xhr.onerror = (xhr) => console.log("Couldn't load " + name); + xhr.send(); }