BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / util / audio.js

audio.js

audio.js 2.5 KiB Download Raw
1var GameAudio =
2{
3 active: false,
4 sounds: {},
5 path: "",
6 volume: 1,
7 multiplay: true,
8 supported: ["mp3", "ogg", "wav", "mp4", "aac"],
9
10 init: function (collection, containingFolder)
11 {
12 console.log("GAME: Loading sounds. (Note: Only supported from online-source, will fail when executed on local files.)");
13
14 try
15 {
16 if (typeof Audio !== "function" && typeof Audio !== "object")
17 {
18 throw new Error("HTML5 Audio is not supported in this browser");
19 }
20
21 if (containingFolder == null)
22 { containingFolder = ""; }
23
24 if (containingFolder != "")
25 { containingFolder += "/"; }
26
27 this.path = containingFolder;
28 this.sounds = {};
29
30 for (var i = 0; i < collection.length; i++)
31 {
32 var entry = collection[i];
33 var name = entry.name;
34 if (!name)
35 { continue; }
36
37 var audio = new Audio();
38 audio.preload = "auto";
39 audio.volume = entry.volume != null ? entry.volume : this.volume;
40 audio.src = this.resolveUrl(entry);
41
42 // Kick off preload without blocking init.
43 audio.load();
44
45 this.sounds[name] = audio;
46 }
47
48 this.active = true;
49 }
50 catch (err)
51 {
52 this.active = false;
53 console.log("GAME: ERROR: Sounds could not be loaded. Sound will not be available.");
54 }
55 },
56
57 resolveUrl: function (entry)
58 {
59 if (entry.url)
60 { return entry.url; }
61
62 var ext = entry.ext || this.pickExtension();
63 if (ext.charAt(0) === ".")
64 { ext = ext.substring(1); }
65
66 return this.path + entry.name + "." + ext;
67 },
68
69 pickExtension: function ()
70 {
71 var probe = new Audio();
72
73 for (var i = 0; i < this.supported.length; i++)
74 {
75 var ext = this.supported[i];
76 var mime = this.mimeFor(ext);
77 if (mime && probe.canPlayType(mime))
78 { return ext; }
79 }
80
81 return "mp3";
82 },
83
84 mimeFor: function (ext)
85 {
86 switch (ext)
87 {
88 case "mp3": return "audio/mpeg";
89 case "ogg": return "audio/ogg";
90 case "wav": return "audio/wav";
91 case "mp4":
92 case "aac": return 'audio/mp4; codecs="mp4a.40.2"';
93 default: return "";
94 }
95 },
96
97 play: function (name)
98 {
99 if (!this.active)
100 { return; }
101
102 var source = this.sounds[name];
103 if (!source)
104 {
105 console.warn("GAME: Sound '" + name + "' was not loaded.");
106 return;
107 }
108
109 var clip = this.multiplay ? source.cloneNode() : source;
110 clip.volume = source.volume;
111
112 if (!this.multiplay)
113 {
114 try { clip.currentTime = 0; }
115 catch (err) { /* ignore seek errors before load */ }
116 }
117
118 var playPromise = clip.play();
119 if (playPromise && typeof playPromise.catch === "function")
120 {
121 playPromise.catch(function ()
122 {
123 // Autoplay policies can reject until a user gesture; ignore.
124 });
125 }
126 }
127};