var GameAudio = { active: false, sounds: {}, path: "", volume: 1, multiplay: true, supported: ["mp3", "ogg", "wav", "mp4", "aac"], init: function (collection, containingFolder) { console.log("GAME: Loading sounds. (Note: Only supported from online-source, will fail when executed on local files.)"); try { if (typeof Audio !== "function" && typeof Audio !== "object") { throw new Error("HTML5 Audio is not supported in this browser"); } if (containingFolder == null) { containingFolder = ""; } if (containingFolder != "") { containingFolder += "/"; } this.path = containingFolder; this.sounds = {}; for (var i = 0; i < collection.length; i++) { var entry = collection[i]; var name = entry.name; if (!name) { continue; } var audio = new Audio(); audio.preload = "auto"; audio.volume = entry.volume != null ? entry.volume : this.volume; audio.src = this.resolveUrl(entry); // Kick off preload without blocking init. audio.load(); this.sounds[name] = audio; } this.active = true; } catch (err) { this.active = false; console.log("GAME: ERROR: Sounds could not be loaded. Sound will not be available."); } }, resolveUrl: function (entry) { if (entry.url) { return entry.url; } var ext = entry.ext || this.pickExtension(); if (ext.charAt(0) === ".") { ext = ext.substring(1); } return this.path + entry.name + "." + ext; }, pickExtension: function () { var probe = new Audio(); for (var i = 0; i < this.supported.length; i++) { var ext = this.supported[i]; var mime = this.mimeFor(ext); if (mime && probe.canPlayType(mime)) { return ext; } } return "mp3"; }, mimeFor: function (ext) { switch (ext) { case "mp3": return "audio/mpeg"; case "ogg": return "audio/ogg"; case "wav": return "audio/wav"; case "mp4": case "aac": return 'audio/mp4; codecs="mp4a.40.2"'; default: return ""; } }, play: function (name) { if (!this.active) { return; } var source = this.sounds[name]; if (!source) { console.warn("GAME: Sound '" + name + "' was not loaded."); return; } var clip = this.multiplay ? source.cloneNode() : source; clip.volume = source.volume; if (!this.multiplay) { try { clip.currentTime = 0; } catch (err) { /* ignore seek errors before load */ } } var playPromise = clip.play(); if (playPromise && typeof playPromise.catch === "function") { playPromise.catch(function () { // Autoplay policies can reject until a user gesture; ignore. }); } } };