comparison core.js @ 1607:e5f1caa513d8

Merge 'default' and 'Dev_main' branch
author Brecht De Man <b.deman@qmul.ac.uk>
date Sun, 17 May 2015 18:40:56 +0100
parents
children 759c2ace3c65
comparison
equal deleted inserted replaced
-1:000000000000 1607:e5f1caa513d8
1 /**
2 * core.js
3 *
4 * Main script to run, calls all other core functions and manages loading/store to backend.
5 * Also contains all global variables.
6 */
7
8 /* create the web audio API context and store in audioContext*/
9 var audioContext; // Hold the browser web audio API
10 var projectXML; // Hold the parsed setup XML
11
12 var testXMLSetups = []; // Hold the parsed test instances
13 var testResultsHolders =[]; // Hold the results from each test for publishing to XML
14 var currentTrackOrder = []; // Hold the current XML tracks in their (randomised) order
15 var currentTestHolder; // Hold any intermediate results during test - metrics
16 var audioEngineContext; // The custome AudioEngine object
17 var projectReturn; // Hold the URL for the return
18 var preTestQuestions = document.createElement('PreTest'); // Store any pre-test question response
19 var postTestQuestions = document.createElement('PostTest'); // Store any post-test question response
20
21 // Add a prototype to the bufferSourceNode to reference to the audioObject holding it
22 AudioBufferSourceNode.prototype.owner = undefined;
23
24 window.onload = function() {
25 // Function called once the browser has loaded all files.
26 // This should perform any initial commands such as structure / loading documents
27
28 // Create a web audio API context
29 // Fixed for cross-browser support
30 var AudioContext = window.AudioContext || window.webkitAudioContext;
31 audioContext = new AudioContext;
32
33 // Create the audio engine object
34 audioEngineContext = new AudioEngine();
35 };
36
37 function loadProjectSpec(url) {
38 // Load the project document from the given URL, decode the XML and instruct audioEngine to get audio data
39 // If url is null, request client to upload project XML document
40 var r = new XMLHttpRequest();
41 r.open('GET',url,true);
42 r.onload = function() {
43 loadProjectSpecCallback(r.response);
44 };
45 r.send();
46 };
47
48 function loadProjectSpecCallback(response) {
49 // Function called after asynchronous download of XML project specification
50 var decode = $.parseXML(response);
51 projectXML = $(decode);
52
53 // Now extract the setup tag
54 var xmlSetup = projectXML.find('setup');
55 // Detect the interface to use and load the relevant javascripts.
56 var interfaceType = xmlSetup[0].attributes['interface'];
57 var interfaceJS = document.createElement('script');
58 interfaceJS.setAttribute("type","text/javascript");
59 if (interfaceType.value == 'APE') {
60 interfaceJS.setAttribute("src","ape.js");
61
62 // APE comes with a css file
63 var css = document.createElement('link');
64 css.rel = 'stylesheet';
65 css.type = 'text/css';
66 css.href = 'ape.css';
67
68 document.getElementsByTagName("head")[0].appendChild(css);
69 }
70 document.getElementsByTagName("head")[0].appendChild(interfaceJS);
71 }
72
73 function createProjectSave(destURL) {
74 // Save the data from interface into XML and send to destURL
75 // If destURL is null then download XML in client
76 // Now time to render file locally
77 var xmlDoc = interfaceXMLSave();
78 if (destURL == "null" || destURL == undefined) {
79 var parent = document.createElement("div");
80 parent.appendChild(xmlDoc);
81 var file = [parent.innerHTML];
82 var bb = new Blob(file,{type : 'application/xml'});
83 var dnlk = window.URL.createObjectURL(bb);
84 var a = document.createElement("a");
85 a.hidden = '';
86 a.href = dnlk;
87 a.download = "save.xml";
88 a.textContent = "Save File";
89
90 var submitDiv = document.getElementById('download-point');
91 submitDiv.appendChild(a);
92 }
93 return submitDiv;
94 }
95
96 function AudioEngine() {
97
98 // Create two output paths, the main outputGain and fooGain.
99 // Output gain is default to 1 and any items for playback route here
100 // Foo gain is used for analysis to ensure paths get processed, but are not heard
101 // because web audio will optimise and any route which does not go to the destination gets ignored.
102 this.outputGain = audioContext.createGain();
103 this.fooGain = audioContext.createGain();
104 this.fooGain.gain = 0;
105
106 // Use this to detect playback state: 0 - stopped, 1 - playing
107 this.status = 0;
108
109 // Connect both gains to output
110 this.outputGain.connect(audioContext.destination);
111 this.fooGain.connect(audioContext.destination);
112
113 // Create the timer Object
114 this.timer = new timer();
115 // Create session metrics
116 this.metric = new sessionMetrics(this);
117
118 this.loopPlayback = false;
119
120 // Create store for new audioObjects
121 this.audioObjects = [];
122
123 this.play = function(){};
124
125 this.stop = function(){};
126
127
128 this.newTrack = function(url) {
129 // Pull data from given URL into new audio buffer
130 // URLs must either be from the same source OR be setup to 'Access-Control-Allow-Origin'
131
132 // Create the audioObject with ID of the new track length;
133 audioObjectId = this.audioObjects.length;
134 this.audioObjects[audioObjectId] = new audioObject(audioObjectId);
135
136 // AudioObject will get track itself.
137 this.audioObjects[audioObjectId].constructTrack(url);
138 };
139
140 }
141
142 function audioObject(id) {
143 // The main buffer object with common control nodes to the AudioEngine
144
145 this.id = id;
146 this.state = 0; // 0 - no data, 1 - ready
147 this.url = null; // Hold the URL given for the output back to the results.
148 this.metric = new metricTracker();
149
150 // Create a buffer and external gain control to allow internal patching of effects and volume leveling.
151 this.bufferNode = undefined;
152 this.outputGain = audioContext.createGain();
153
154 // Default output gain to be zero
155 this.outputGain.gain.value = 0.0;
156
157 // Connect buffer to the audio graph
158 this.outputGain.connect(audioEngineContext.outputGain);
159
160 // the audiobuffer is not designed for multi-start playback
161 // When stopeed, the buffer node is deleted and recreated with the stored buffer.
162 this.buffer;
163
164 this.play = function(startTime) {
165 this.bufferNode = audioContext.createBufferSource();
166 this.bufferNode.connect(this.outputGain);
167 this.bufferNode.buffer = this.buffer;
168 this.bufferNode.loop = audioEngineContext.loopPlayback;
169 this.bufferNode.start(startTime);
170 };
171
172 this.stop = function() {
173 if (this.bufferNode != undefined)
174 {
175 this.bufferNode.stop(0);
176 this.bufferNode = undefined;
177 }
178 };
179
180 this.constructTrack = function(url) {
181 var request = new XMLHttpRequest();
182 this.url = url;
183 request.open('GET',url,true);
184 request.responseType = 'arraybuffer';
185
186 var audioObj = this;
187
188 // Create callback to decode the data asynchronously
189 request.onloadend = function() {
190 audioContext.decodeAudioData(request.response, function(decodedData) {
191 audioObj.buffer = decodedData;
192 audioObj.state = 1;
193 }, function(){
194 // Should only be called if there was an error, but sometimes gets called continuously
195 // Check here if the error is genuine
196 if (audioObj.state == 0 || audioObj.buffer == undefined) {
197 // Genuine error
198 console.log('FATAL - Error loading buffer on '+audioObj.id);
199 }
200 });
201 };
202 request.send();
203 };
204
205 }
206
207 function timer()
208 {
209 /* Timer object used in audioEngine to keep track of session timings
210 * Uses the timer of the web audio API, so sample resolution
211 */
212 this.testStarted = false;
213 this.testStartTime = 0;
214 this.testDuration = 0;
215 this.minimumTestTime = 0; // No minimum test time
216 this.startTest = function()
217 {
218 if (this.testStarted == false)
219 {
220 this.testStartTime = audioContext.currentTime;
221 this.testStarted = true;
222 this.updateTestTime();
223 audioEngineContext.metric.initialiseTest();
224 }
225 };
226 this.stopTest = function()
227 {
228 if (this.testStarted)
229 {
230 this.testDuration = this.getTestTime();
231 this.testStarted = false;
232 } else {
233 console.log('ERR: Test tried to end before beginning');
234 }
235 };
236 this.updateTestTime = function()
237 {
238 if (this.testStarted)
239 {
240 this.testDuration = audioContext.currentTime - this.testStartTime;
241 }
242 };
243 this.getTestTime = function()
244 {
245 this.updateTestTime();
246 return this.testDuration;
247 };
248 }
249
250 function sessionMetrics(engine)
251 {
252 /* Used by audioEngine to link to audioObjects to minimise the timer call timers;
253 */
254 this.engine = engine;
255 this.lastClicked = -1;
256 this.data = -1;
257 this.initialiseTest = function(){};
258 }
259
260 function metricTracker()
261 {
262 /* Custom object to track and collect metric data
263 * Used only inside the audioObjects object.
264 */
265
266 this.listenedTimer = 0;
267 this.listenStart = 0;
268 this.initialPosition = -1;
269 this.movementTracker = [];
270 this.wasListenedTo = false;
271 this.wasMoved = false;
272 this.hasComments = false;
273
274 this.initialised = function(position)
275 {
276 if (this.initialPosition == -1) {
277 this.initialPosition = position;
278 }
279 };
280
281 this.moved = function(time,position)
282 {
283 this.wasMoved = true;
284 this.movementTracker[this.movementTracker.length] = [time, position];
285 };
286
287 this.listening = function(time)
288 {
289 if (this.listenStart == 0)
290 {
291 this.wasListenedTo = true;
292 this.listenStart = time;
293 } else {
294 this.listenedTimer += (time - this.listenStart);
295 this.listenStart = 0;
296 }
297 };
298 }
299
300 function randomiseOrder(input)
301 {
302 // This takes an array of information and randomises the order
303 var N = input.length;
304 var K = N;
305 var holdArr = [];
306 for (var n=0; n<N; n++)
307 {
308 // First pick a random number
309 var r = Math.random();
310 // Multiply and floor by the number of elements left
311 r = Math.floor(r*input.length);
312 // Pick out that element and delete from the array
313 holdArr.push(input.splice(r,1)[0]);
314 }
315 return holdArr;
316 }