annotate core.js @ 905:b64ddb277eb0

Merge from the default branch
author Nicholas Jillings <n.g.r.jillings@se14.qmul.ac.uk>
date Thu, 04 Jun 2015 10:36:05 +0100
parents
children 6d37dd0f1dc7 35682e8e1159
rev   line source
n@905 1 /**
n@905 2 * core.js
n@905 3 *
n@905 4 * Main script to run, calls all other core functions and manages loading/store to backend.
n@905 5 * Also contains all global variables.
n@905 6 */
n@905 7
n@905 8 /* create the web audio API context and store in audioContext*/
n@905 9 var audioContext; // Hold the browser web audio API
n@905 10 var projectXML; // Hold the parsed setup XML
n@905 11 var popup; // Hold the interfacePopup object
n@905 12 var testState;
n@905 13 var currentState; // Keep track of the current state (pre/post test, which test, final test? first test?)
n@905 14 var currentTrackOrder = []; // Hold the current XML tracks in their (randomised) order
n@905 15 var audioEngineContext; // The custome AudioEngine object
n@905 16 var projectReturn; // Hold the URL for the return
n@905 17
n@905 18
n@905 19 // Add a prototype to the bufferSourceNode to reference to the audioObject holding it
n@905 20 AudioBufferSourceNode.prototype.owner = undefined;
n@905 21
n@905 22 window.onload = function() {
n@905 23 // Function called once the browser has loaded all files.
n@905 24 // This should perform any initial commands such as structure / loading documents
n@905 25
n@905 26 // Create a web audio API context
n@905 27 // Fixed for cross-browser support
n@905 28 var AudioContext = window.AudioContext || window.webkitAudioContext;
n@905 29 audioContext = new AudioContext;
n@905 30
n@905 31 // Create test state
n@905 32 testState = new stateMachine();
n@905 33
n@905 34 // Create the audio engine object
n@905 35 audioEngineContext = new AudioEngine();
n@905 36
n@905 37 // Create the popup interface object
n@905 38 popup = new interfacePopup();
n@905 39 };
n@905 40
n@905 41 function interfacePopup() {
n@905 42 // Creates an object to manage the popup
n@905 43 this.popup = null;
n@905 44 this.popupContent = null;
n@905 45 this.popupButton = null;
n@905 46 this.popupOptions = null;
n@905 47 this.currentIndex = null;
n@905 48 this.responses = null;
n@905 49 this.createPopup = function(){
n@905 50 // Create popup window interface
n@905 51 var insertPoint = document.getElementById("topLevelBody");
n@905 52 var blank = document.createElement('div');
n@905 53 blank.className = 'testHalt';
n@905 54
n@905 55 this.popup = document.createElement('div');
n@905 56 this.popup.id = 'popupHolder';
n@905 57 this.popup.className = 'popupHolder';
n@905 58 this.popup.style.position = 'absolute';
n@905 59 this.popup.style.left = (window.innerWidth/2)-250 + 'px';
n@905 60 this.popup.style.top = (window.innerHeight/2)-125 + 'px';
n@905 61
n@905 62 this.popupContent = document.createElement('div');
n@905 63 this.popupContent.id = 'popupContent';
n@905 64 this.popupContent.style.marginTop = '25px';
n@905 65 this.popupContent.align = 'center';
n@905 66 this.popup.appendChild(this.popupContent);
n@905 67
n@905 68 this.popupButton = document.createElement('button');
n@905 69 this.popupButton.className = 'popupButton';
n@905 70 this.popupButton.innerHTML = 'Next';
n@905 71 this.popupButton.onclick = function(){popup.buttonClicked();};
n@905 72 insertPoint.appendChild(this.popup);
n@905 73 insertPoint.appendChild(blank);
n@905 74 };
n@905 75
n@905 76 this.showPopup = function(){
n@905 77 if (this.popup == null || this.popup == undefined) {
n@905 78 this.createPopup();
n@905 79 }
n@905 80 this.popup.style.zIndex = 3;
n@905 81 this.popup.style.visibility = 'visible';
n@905 82 var blank = document.getElementsByClassName('testHalt')[0];
n@905 83 blank.style.zIndex = 2;
n@905 84 blank.style.visibility = 'visible';
n@905 85 };
n@905 86
n@905 87 this.hidePopup = function(){
n@905 88 this.popup.style.zIndex = -1;
n@905 89 this.popup.style.visibility = 'hidden';
n@905 90 var blank = document.getElementsByClassName('testHalt')[0];
n@905 91 blank.style.zIndex = -2;
n@905 92 blank.style.visibility = 'hidden';
n@905 93 };
n@905 94
n@905 95 this.postNode = function() {
n@905 96 // This will take the node from the popupOptions and display it
n@905 97 var node = this.popupOptions[this.currentIndex];
n@905 98 this.popupContent.innerHTML = null;
n@905 99 if (node.nodeName == 'statement') {
n@905 100 var span = document.createElement('span');
n@905 101 span.textContent = node.textContent;
n@905 102 this.popupContent.appendChild(span);
n@905 103 } else if (node.nodeName == 'question') {
n@905 104 var span = document.createElement('span');
n@905 105 span.textContent = node.textContent;
n@905 106 var textArea = document.createElement('textarea');
n@905 107 var br = document.createElement('br');
n@905 108 this.popupContent.appendChild(span);
n@905 109 this.popupContent.appendChild(br);
n@905 110 this.popupContent.appendChild(textArea);
n@905 111 this.popupContent.childNodes[2].focus();
n@905 112 }
n@905 113 this.popupContent.appendChild(this.popupButton);
n@905 114 };
n@905 115
n@905 116 this.initState = function(node) {
n@905 117 //Call this with your preTest and postTest nodes when needed to
n@905 118 // initialise the popup procedure.
n@905 119 this.popupOptions = $(node).children();
n@905 120 if (this.popupOptions.length > 0) {
n@905 121 if (node.nodeName == 'preTest' || node.nodeName == 'PreTest') {
n@905 122 this.responses = document.createElement('PreTest');
n@905 123 } else if (node.nodeName == 'postTest' || node.nodeName == 'PostTest') {
n@905 124 this.responses = document.createElement('PostTest');
n@905 125 } else {
n@905 126 console.log ('WARNING - popup node neither pre or post!');
n@905 127 this.responses = document.createElement('responses');
n@905 128 }
n@905 129 this.currentIndex = 0;
n@905 130 this.showPopup();
n@905 131 this.postNode();
n@905 132 }
n@905 133 };
n@905 134
n@905 135 this.buttonClicked = function() {
n@905 136 // Each time the popup button is clicked!
n@905 137 var node = this.popupOptions[this.currentIndex];
n@905 138 if (node.nodeName == 'question') {
n@905 139 // Must extract the question data
n@905 140 var mandatory = node.attributes['mandatory'];
n@905 141 if (mandatory == undefined) {
n@905 142 mandatory = false;
n@905 143 } else {
n@905 144 if (mandatory.value == 'true'){mandatory = true;}
n@905 145 else {mandatory = false;}
n@905 146 }
n@905 147 var textArea = $(popup.popupContent).find('textarea')[0];
n@905 148 if (mandatory == true && textArea.value.length == 0) {
n@905 149 alert('This question is mandatory');
n@905 150 return;
n@905 151 } else {
n@905 152 // Save the text content
n@905 153 var hold = document.createElement('comment');
n@905 154 hold.id = node.attributes['id'].value;
n@905 155 hold.innerHTML = textArea.value;
n@905 156 console.log("Question: "+ node.textContent);
n@905 157 console.log("Question Response: "+ textArea.value);
n@905 158 this.responses.appendChild(hold);
n@905 159 }
n@905 160 }
n@905 161 this.currentIndex++;
n@905 162 if (this.currentIndex < this.popupOptions.length) {
n@905 163 this.postNode();
n@905 164 } else {
n@905 165 // Reached the end of the popupOptions
n@905 166 this.hidePopup();
n@905 167 if (this.responses.nodeName == testState.stateResults[testState.stateIndex].nodeName) {
n@905 168 testState.stateResults[testState.stateIndex] = this.responses;
n@905 169 } else {
n@905 170 testState.stateResults[testState.stateIndex].appendChild(this.responses);
n@905 171 }
n@905 172 advanceState();
n@905 173 }
n@905 174 };
n@905 175 }
n@905 176
n@905 177 function advanceState()
n@905 178 {
n@905 179 // Just for complete clarity
n@905 180 testState.advanceState();
n@905 181 }
n@905 182
n@905 183 function stateMachine()
n@905 184 {
n@905 185 // Object prototype for tracking and managing the test state
n@905 186 this.stateMap = [];
n@905 187 this.stateIndex = null;
n@905 188 this.currentStateMap = [];
n@905 189 this.currentIndex = null;
n@905 190 this.currentTestId = 0;
n@905 191 this.stateResults = [];
n@905 192 this.timerCallBackHolders = null;
n@905 193 this.initialise = function(){
n@905 194 if (this.stateMap.length > 0) {
n@905 195 if(this.stateIndex != null) {
n@905 196 console.log('NOTE - State already initialise');
n@905 197 }
n@905 198 this.stateIndex = -1;
n@905 199 var that = this;
n@905 200 for (var id=0; id<this.stateMap.length; id++){
n@905 201 var name = this.stateMap[id].nodeName;
n@905 202 var obj = document.createElement(name);
n@905 203 if (name == "audioHolder") {
n@905 204 obj.id = this.stateMap[id].id;
n@905 205 }
n@905 206 this.stateResults.push(obj);
n@905 207 }
n@905 208 } else {
n@905 209 conolse.log('FATAL - StateMap not correctly constructed. EMPTY_STATE_MAP');
n@905 210 }
n@905 211 };
n@905 212 this.advanceState = function(){
n@905 213 if (this.stateIndex == null) {
n@905 214 this.initialise();
n@905 215 }
n@905 216 if (this.stateIndex == -1) {
n@905 217 console.log('Starting test...');
n@905 218 }
n@905 219 if (this.currentIndex == null){
n@905 220 if (this.currentStateMap.nodeName == "audioHolder") {
n@905 221 // Save current page
n@905 222 this.testPageCompleted(this.stateResults[this.stateIndex],this.currentStateMap,this.currentTestId);
n@905 223 this.currentTestId++;
n@905 224 }
n@905 225 this.stateIndex++;
n@905 226 if (this.stateIndex >= this.stateMap.length) {
n@905 227 console.log('Test Completed');
n@905 228 createProjectSave(projectReturn);
n@905 229 } else {
n@905 230 this.currentStateMap = this.stateMap[this.stateIndex];
n@905 231 if (this.currentStateMap.nodeName == "audioHolder") {
n@905 232 console.log('Loading test page');
n@905 233 loadTest(this.currentStateMap);
n@905 234 this.initialiseInnerState(this.currentStateMap);
n@905 235 } else if (this.currentStateMap.nodeName == "PreTest" || this.currentStateMap.nodeName == "PostTest") {
n@905 236 if (this.currentStateMap.childElementCount >= 1) {
n@905 237 popup.initState(this.currentStateMap);
n@905 238 } else {
n@905 239 this.advanceState();
n@905 240 }
n@905 241 } else {
n@905 242 this.advanceState();
n@905 243 }
n@905 244 }
n@905 245 } else {
n@905 246 this.advanceInnerState();
n@905 247 }
n@905 248 };
n@905 249
n@905 250 this.testPageCompleted = function(store, testXML, testId) {
n@905 251 // Function called each time a test page has been completed
n@905 252 // Can be used to over-rule default behaviour
n@905 253
n@905 254 pageXMLSave(store, testXML, testId);
n@905 255 }
n@905 256
n@905 257 this.initialiseInnerState = function(testXML) {
n@905 258 // Parses the received testXML for pre and post test options
n@905 259 this.currentStateMap = [];
n@905 260 var preTest = $(testXML).find('PreTest')[0];
n@905 261 var postTest = $(testXML).find('PostTest')[0];
n@905 262 if (preTest == undefined) {preTest = document.createElement("preTest");}
n@905 263 if (postTest == undefined){postTest= document.createElement("postTest");}
n@905 264 this.currentStateMap.push(preTest);
n@905 265 this.currentStateMap.push(testXML);
n@905 266 this.currentStateMap.push(postTest);
n@905 267 this.currentIndex = -1;
n@905 268 this.advanceInnerState();
n@905 269 }
n@905 270
n@905 271 this.advanceInnerState = function() {
n@905 272 this.currentIndex++;
n@905 273 if (this.currentIndex >= this.currentStateMap.length) {
n@905 274 this.currentIndex = null;
n@905 275 this.currentStateMap = this.stateMap[this.stateIndex];
n@905 276 this.advanceState();
n@905 277 } else {
n@905 278 if (this.currentStateMap[this.currentIndex].nodeName == "audioHolder") {
n@905 279 console.log("Loading test page"+this.currentTestId);
n@905 280 } else if (this.currentStateMap[this.currentIndex].nodeName == "PreTest") {
n@905 281 popup.initState(this.currentStateMap[this.currentIndex]);
n@905 282 } else if (this.currentStateMap[this.currentIndex].nodeName == "PostTest") {
n@905 283 popup.initState(this.currentStateMap[this.currentIndex]);
n@905 284 } else {
n@905 285 this.advanceInnerState();
n@905 286 }
n@905 287 }
n@905 288 }
n@905 289
n@905 290 this.previousState = function(){};
n@905 291 }
n@905 292
n@905 293 function testEnded(testId)
n@905 294 {
n@905 295 pageXMLSave(testId);
n@905 296 if (testXMLSetups.length-1 > testId)
n@905 297 {
n@905 298 // Yes we have another test to perform
n@905 299 testId = (Number(testId)+1);
n@905 300 currentState = 'testRun-'+testId;
n@905 301 loadTest(testId);
n@905 302 } else {
n@905 303 console.log('Testing Completed!');
n@905 304 currentState = 'postTest';
n@905 305 // Check for any post tests
n@905 306 var xmlSetup = projectXML.find('setup');
n@905 307 var postTest = xmlSetup.find('PostTest')[0];
n@905 308 popup.initState(postTest);
n@905 309 }
n@905 310 }
n@905 311
n@905 312 function loadProjectSpec(url) {
n@905 313 // Load the project document from the given URL, decode the XML and instruct audioEngine to get audio data
n@905 314 // If url is null, request client to upload project XML document
n@905 315 var r = new XMLHttpRequest();
n@905 316 r.open('GET',url,true);
n@905 317 r.onload = function() {
n@905 318 loadProjectSpecCallback(r.response);
n@905 319 };
n@905 320 r.send();
n@905 321 };
n@905 322
n@905 323 function loadProjectSpecCallback(response) {
n@905 324 // Function called after asynchronous download of XML project specification
n@905 325 var decode = $.parseXML(response);
n@905 326 projectXML = $(decode);
n@905 327
n@905 328 // Now extract the setup tag
n@905 329 var xmlSetup = projectXML.find('setup');
n@905 330 // Detect the interface to use and load the relevant javascripts.
n@905 331 var interfaceType = xmlSetup[0].attributes['interface'];
n@905 332 var interfaceJS = document.createElement('script');
n@905 333 interfaceJS.setAttribute("type","text/javascript");
n@905 334 if (interfaceType.value == 'APE') {
n@905 335 interfaceJS.setAttribute("src","ape.js");
n@905 336
n@905 337 // APE comes with a css file
n@905 338 var css = document.createElement('link');
n@905 339 css.rel = 'stylesheet';
n@905 340 css.type = 'text/css';
n@905 341 css.href = 'ape.css';
n@905 342
n@905 343 document.getElementsByTagName("head")[0].appendChild(css);
n@905 344 }
n@905 345 document.getElementsByTagName("head")[0].appendChild(interfaceJS);
n@905 346
n@905 347 // Define window callbacks for interface
n@905 348 window.onresize = function(event){resizeWindow(event);};
n@905 349 }
n@905 350
n@905 351 function createProjectSave(destURL) {
n@905 352 // Save the data from interface into XML and send to destURL
n@905 353 // If destURL is null then download XML in client
n@905 354 // Now time to render file locally
n@905 355 var xmlDoc = interfaceXMLSave();
n@905 356 var parent = document.createElement("div");
n@905 357 parent.appendChild(xmlDoc);
n@905 358 var file = [parent.innerHTML];
n@905 359 if (destURL == "null" || destURL == undefined) {
n@905 360 var bb = new Blob(file,{type : 'application/xml'});
n@905 361 var dnlk = window.URL.createObjectURL(bb);
n@905 362 var a = document.createElement("a");
n@905 363 a.hidden = '';
n@905 364 a.href = dnlk;
n@905 365 a.download = "save.xml";
n@905 366 a.textContent = "Save File";
n@905 367
n@905 368 var submitDiv = document.getElementById('download-point');
n@905 369 submitDiv.appendChild(a);
n@905 370 popup.showPopup();
n@905 371 popup.popupContent.innerHTML = null;
n@905 372 popup.popupContent.appendChild(submitDiv)
n@905 373 } else {
n@905 374 var xmlhttp = new XMLHttpRequest;
n@905 375 xmlhttp.open("POST",destURL,true);
n@905 376 xmlhttp.setRequestHeader('Content-Type', 'text/xml');
n@905 377 xmlhttp.onerror = function(){
n@905 378 console.log('Error saving file to server! Presenting download locally');
n@905 379 createProjectSave(null);
n@905 380 };
n@905 381 xmlhttp.onreadystatechange = function() {
n@905 382 console.log(xmlhttp.status);
n@905 383 if (xmlhttp.status != 200 && xmlhttp.readyState == 4) {
n@905 384 createProjectSave(null);
n@905 385 }
n@905 386 };
n@905 387 xmlhttp.send(file);
n@905 388 }
n@905 389 return submitDiv;
n@905 390 }
n@905 391
n@905 392 // Only other global function which must be defined in the interface class. Determines how to create the XML document.
n@905 393 function interfaceXMLSave(){
n@905 394 // Create the XML string to be exported with results
n@905 395 var xmlDoc = document.createElement("BrowserEvaluationResult");
n@905 396 xmlDoc.appendChild(returnDateNode());
n@905 397 for (var i=0; i<testState.stateResults.length; i++)
n@905 398 {
n@905 399 xmlDoc.appendChild(testState.stateResults[i]);
n@905 400 }
n@905 401
n@905 402 return xmlDoc;
n@905 403 }
n@905 404
n@905 405 function AudioEngine() {
n@905 406
n@905 407 // Create two output paths, the main outputGain and fooGain.
n@905 408 // Output gain is default to 1 and any items for playback route here
n@905 409 // Foo gain is used for analysis to ensure paths get processed, but are not heard
n@905 410 // because web audio will optimise and any route which does not go to the destination gets ignored.
n@905 411 this.outputGain = audioContext.createGain();
n@905 412 this.fooGain = audioContext.createGain();
n@905 413 this.fooGain.gain = 0;
n@905 414
n@905 415 // Use this to detect playback state: 0 - stopped, 1 - playing
n@905 416 this.status = 0;
n@905 417 this.audioObjectsReady = false;
n@905 418
n@905 419 // Connect both gains to output
n@905 420 this.outputGain.connect(audioContext.destination);
n@905 421 this.fooGain.connect(audioContext.destination);
n@905 422
n@905 423 // Create the timer Object
n@905 424 this.timer = new timer();
n@905 425 // Create session metrics
n@905 426 this.metric = new sessionMetrics(this);
n@905 427
n@905 428 this.loopPlayback = false;
n@905 429
n@905 430 // Create store for new audioObjects
n@905 431 this.audioObjects = [];
n@905 432
n@905 433 this.play = function() {
n@905 434 // Start the timer and set the audioEngine state to playing (1)
n@905 435 if (this.status == 0) {
n@905 436 // Check if all audioObjects are ready
n@905 437 if (this.audioObjectsReady == false) {
n@905 438 this.audioObjectsReady = this.checkAllReady();
n@905 439 }
n@905 440 if (this.audioObjectsReady == true) {
n@905 441 this.timer.startTest();
n@905 442 if (this.loopPlayback) {
n@905 443 for(var i=0; i<this.audioObjects.length; i++) {
n@905 444 this.audioObjects[i].play(this.timer.getTestTime()+1);
n@905 445 }
n@905 446 }
n@905 447 this.status = 1;
n@905 448 }
n@905 449 }
n@905 450 };
n@905 451
n@905 452 this.stop = function() {
n@905 453 // Send stop and reset command to all playback buffers and set audioEngine state to stopped (1)
n@905 454 if (this.status == 1) {
n@905 455 for (var i=0; i<this.audioObjects.length; i++)
n@905 456 {
n@905 457 this.audioObjects[i].stop();
n@905 458 }
n@905 459 this.status = 0;
n@905 460 }
n@905 461 };
n@905 462
n@905 463
n@905 464 this.newTrack = function(url) {
n@905 465 // Pull data from given URL into new audio buffer
n@905 466 // URLs must either be from the same source OR be setup to 'Access-Control-Allow-Origin'
n@905 467
n@905 468 // Create the audioObject with ID of the new track length;
n@905 469 audioObjectId = this.audioObjects.length;
n@905 470 this.audioObjects[audioObjectId] = new audioObject(audioObjectId);
n@905 471
n@905 472 // AudioObject will get track itself.
n@905 473 this.audioObjects[audioObjectId].constructTrack(url);
n@905 474 };
n@905 475
n@905 476 this.newTestPage = function() {
n@905 477 this.state = 0;
n@905 478 this.audioObjectsReady = false;
n@905 479 this.metric.reset();
n@905 480 this.audioObjects = [];
n@905 481 };
n@905 482
n@905 483 this.checkAllPlayed = function() {
n@905 484 arr = [];
n@905 485 for (var id=0; id<this.audioObjects.length; id++) {
n@905 486 if (this.audioObjects[id].metric.wasListenedTo == false) {
n@905 487 arr.push(this.audioObjects[id].id);
n@905 488 }
n@905 489 }
n@905 490 return arr;
n@905 491 };
n@905 492
n@905 493 this.checkAllReady = function() {
n@905 494 var ready = true;
n@905 495 for (var i=0; i<this.audioObjects.length; i++) {
n@905 496 if (this.audioObjects[i].state == 0) {
n@905 497 // Track not ready
n@905 498 console.log('WAIT -- audioObject '+i+' not ready yet!');
n@905 499 ready = false;
n@905 500 };
n@905 501 }
n@905 502 return ready;
n@905 503 };
n@905 504
n@905 505 }
n@905 506
n@905 507 function audioObject(id) {
n@905 508 // The main buffer object with common control nodes to the AudioEngine
n@905 509
n@905 510 this.id = id;
n@905 511 this.state = 0; // 0 - no data, 1 - ready
n@905 512 this.url = null; // Hold the URL given for the output back to the results.
n@905 513 this.metric = new metricTracker(this);
n@905 514
n@905 515 // Create a buffer and external gain control to allow internal patching of effects and volume leveling.
n@905 516 this.bufferNode = undefined;
n@905 517 this.outputGain = audioContext.createGain();
n@905 518
n@905 519 // Default output gain to be zero
n@905 520 this.outputGain.gain.value = 0.0;
n@905 521
n@905 522 // Connect buffer to the audio graph
n@905 523 this.outputGain.connect(audioEngineContext.outputGain);
n@905 524
n@905 525 // the audiobuffer is not designed for multi-start playback
n@905 526 // When stopeed, the buffer node is deleted and recreated with the stored buffer.
n@905 527 this.buffer;
n@905 528
n@905 529 this.loopStart = function() {
n@905 530 this.outputGain.gain.value = 1.0;
n@905 531 this.metric.startListening(audioEngineContext.timer.getTestTime());
n@905 532 }
n@905 533
n@905 534 this.loopStop = function() {
n@905 535 if (this.outputGain.gain.value != 0.0) {
n@905 536 this.outputGain.gain.value = 0.0;
n@905 537 this.metric.stopListening(audioEngineContext.timer.getTestTime());
n@905 538 }
n@905 539 }
n@905 540
n@905 541 this.play = function(startTime) {
n@905 542 this.bufferNode = audioContext.createBufferSource();
n@905 543 this.bufferNode.owner = this;
n@905 544 this.bufferNode.connect(this.outputGain);
n@905 545 this.bufferNode.buffer = this.buffer;
n@905 546 this.bufferNode.loop = audioEngineContext.loopPlayback;
n@905 547 this.bufferNode.onended = function() {
n@905 548 // Safari does not like using 'this' to reference the calling object!
n@905 549 event.srcElement.owner.metric.stopListening(audioEngineContext.timer.getTestTime());
n@905 550 };
n@905 551 if (this.bufferNode.loop == false) {
n@905 552 this.metric.startListening(audioEngineContext.timer.getTestTime());
n@905 553 }
n@905 554 this.bufferNode.start(startTime);
n@905 555 };
n@905 556
n@905 557 this.stop = function() {
n@905 558 if (this.bufferNode != undefined)
n@905 559 {
n@905 560 this.bufferNode.stop(0);
n@905 561 this.bufferNode = undefined;
n@905 562 this.metric.stopListening(audioEngineContext.timer.getTestTime());
n@905 563 }
n@905 564 };
n@905 565
n@905 566 this.getCurrentPosition = function() {
n@905 567 var time = audioEngineContext.timer.getTestTime();
n@905 568 if (this.bufferNode != undefined) {
n@905 569 if (this.bufferNode.loop == true) {
n@905 570 if (audioEngineContext.status == 1) {
n@905 571 return time%this.buffer.duration;
n@905 572 } else {
n@905 573 return 0;
n@905 574 }
n@905 575 } else {
n@905 576 if (this.metric.listenHold) {
n@905 577 return time - this.metric.listenStart;
n@905 578 } else {
n@905 579 return 0;
n@905 580 }
n@905 581 }
n@905 582 } else {
n@905 583 return 0;
n@905 584 }
n@905 585 };
n@905 586
n@905 587 this.constructTrack = function(url) {
n@905 588 var request = new XMLHttpRequest();
n@905 589 this.url = url;
n@905 590 request.open('GET',url,true);
n@905 591 request.responseType = 'arraybuffer';
n@905 592
n@905 593 var audioObj = this;
n@905 594
n@905 595 // Create callback to decode the data asynchronously
n@905 596 request.onloadend = function() {
n@905 597 audioContext.decodeAudioData(request.response, function(decodedData) {
n@905 598 audioObj.buffer = decodedData;
n@905 599 audioObj.state = 1;
n@905 600 }, function(){
n@905 601 // Should only be called if there was an error, but sometimes gets called continuously
n@905 602 // Check here if the error is genuine
n@905 603 if (audioObj.state == 0 || audioObj.buffer == undefined) {
n@905 604 // Genuine error
n@905 605 console.log('FATAL - Error loading buffer on '+audioObj.id);
n@905 606 }
n@905 607 });
n@905 608 };
n@905 609 request.send();
n@905 610 };
n@905 611
n@905 612 }
n@905 613
n@905 614 function timer()
n@905 615 {
n@905 616 /* Timer object used in audioEngine to keep track of session timings
n@905 617 * Uses the timer of the web audio API, so sample resolution
n@905 618 */
n@905 619 this.testStarted = false;
n@905 620 this.testStartTime = 0;
n@905 621 this.testDuration = 0;
n@905 622 this.minimumTestTime = 0; // No minimum test time
n@905 623 this.startTest = function()
n@905 624 {
n@905 625 if (this.testStarted == false)
n@905 626 {
n@905 627 this.testStartTime = audioContext.currentTime;
n@905 628 this.testStarted = true;
n@905 629 this.updateTestTime();
n@905 630 audioEngineContext.metric.initialiseTest();
n@905 631 }
n@905 632 };
n@905 633 this.stopTest = function()
n@905 634 {
n@905 635 if (this.testStarted)
n@905 636 {
n@905 637 this.testDuration = this.getTestTime();
n@905 638 this.testStarted = false;
n@905 639 } else {
n@905 640 console.log('ERR: Test tried to end before beginning');
n@905 641 }
n@905 642 };
n@905 643 this.updateTestTime = function()
n@905 644 {
n@905 645 if (this.testStarted)
n@905 646 {
n@905 647 this.testDuration = audioContext.currentTime - this.testStartTime;
n@905 648 }
n@905 649 };
n@905 650 this.getTestTime = function()
n@905 651 {
n@905 652 this.updateTestTime();
n@905 653 return this.testDuration;
n@905 654 };
n@905 655 }
n@905 656
n@905 657 function sessionMetrics(engine)
n@905 658 {
n@905 659 /* Used by audioEngine to link to audioObjects to minimise the timer call timers;
n@905 660 */
n@905 661 this.engine = engine;
n@905 662 this.lastClicked = -1;
n@905 663 this.data = -1;
n@905 664 this.reset = function() {
n@905 665 this.lastClicked = -1;
n@905 666 this.data = -1;
n@905 667 };
n@905 668 this.initialiseTest = function(){};
n@905 669 }
n@905 670
n@905 671 function metricTracker(caller)
n@905 672 {
n@905 673 /* Custom object to track and collect metric data
n@905 674 * Used only inside the audioObjects object.
n@905 675 */
n@905 676
n@905 677 this.listenedTimer = 0;
n@905 678 this.listenStart = 0;
n@905 679 this.listenHold = false;
n@905 680 this.initialPosition = -1;
n@905 681 this.movementTracker = [];
n@905 682 this.listenTracker =[];
n@905 683 this.wasListenedTo = false;
n@905 684 this.wasMoved = false;
n@905 685 this.hasComments = false;
n@905 686 this.parent = caller;
n@905 687
n@905 688 this.initialised = function(position)
n@905 689 {
n@905 690 if (this.initialPosition == -1) {
n@905 691 this.initialPosition = position;
n@905 692 }
n@905 693 };
n@905 694
n@905 695 this.moved = function(time,position)
n@905 696 {
n@905 697 this.wasMoved = true;
n@905 698 this.movementTracker[this.movementTracker.length] = [time, position];
n@905 699 };
n@905 700
n@905 701 this.startListening = function(time)
n@905 702 {
n@905 703 if (this.listenHold == false)
n@905 704 {
n@905 705 this.wasListenedTo = true;
n@905 706 this.listenStart = time;
n@905 707 this.listenHold = true;
n@905 708
n@905 709 var evnt = document.createElement('event');
n@905 710 var testTime = document.createElement('testTime');
n@905 711 testTime.setAttribute('start',time);
n@905 712 var bufferTime = document.createElement('bufferTime');
n@905 713 bufferTime.setAttribute('start',this.parent.getCurrentPosition());
n@905 714 evnt.appendChild(testTime);
n@905 715 evnt.appendChild(bufferTime);
n@905 716 this.listenTracker.push(evnt);
n@905 717
n@905 718 console.log('slider ' + this.parent.id + ' played (' + time + ')'); // DEBUG/SAFETY: show played slider id
n@905 719 }
n@905 720 };
n@905 721
n@905 722 this.stopListening = function(time)
n@905 723 {
n@905 724 if (this.listenHold == true)
n@905 725 {
n@905 726 var diff = time - this.listenStart;
n@905 727 this.listenedTimer += (diff);
n@905 728 this.listenStart = 0;
n@905 729 this.listenHold = false;
n@905 730
n@905 731 var evnt = this.listenTracker[this.listenTracker.length-1];
n@905 732 var testTime = evnt.getElementsByTagName('testTime')[0];
n@905 733 var bufferTime = evnt.getElementsByTagName('bufferTime')[0];
n@905 734 testTime.setAttribute('stop',time);
n@905 735 bufferTime.setAttribute('stop',this.parent.getCurrentPosition());
n@905 736 console.log('slider ' + this.parent.id + ' played for (' + diff + ')'); // DEBUG/SAFETY: show played slider id
n@905 737 }
n@905 738 };
n@905 739 }
n@905 740
n@905 741 function randomiseOrder(input)
n@905 742 {
n@905 743 // This takes an array of information and randomises the order
n@905 744 var N = input.length;
n@905 745 var K = N;
n@905 746 var holdArr = [];
n@905 747 for (var n=0; n<N; n++)
n@905 748 {
n@905 749 // First pick a random number
n@905 750 var r = Math.random();
n@905 751 // Multiply and floor by the number of elements left
n@905 752 r = Math.floor(r*input.length);
n@905 753 // Pick out that element and delete from the array
n@905 754 holdArr.push(input.splice(r,1)[0]);
n@905 755 }
n@905 756 return holdArr;
n@905 757 }
n@905 758
n@905 759 function returnDateNode()
n@905 760 {
n@905 761 // Create an XML Node for the Date and Time a test was conducted
n@905 762 // Structure is
n@905 763 // <datetime>
n@905 764 // <date year="##" month="##" day="##">DD/MM/YY</date>
n@905 765 // <time hour="##" minute="##" sec="##">HH:MM:SS</time>
n@905 766 // </datetime>
n@905 767 var dateTime = new Date();
n@905 768 var year = document.createAttribute('year');
n@905 769 var month = document.createAttribute('month');
n@905 770 var day = document.createAttribute('day');
n@905 771 var hour = document.createAttribute('hour');
n@905 772 var minute = document.createAttribute('minute');
n@905 773 var secs = document.createAttribute('secs');
n@905 774
n@905 775 year.nodeValue = dateTime.getFullYear();
n@905 776 month.nodeValue = dateTime.getMonth()+1;
n@905 777 day.nodeValue = dateTime.getDate();
n@905 778 hour.nodeValue = dateTime.getHours();
n@905 779 minute.nodeValue = dateTime.getMinutes();
n@905 780 secs.nodeValue = dateTime.getSeconds();
n@905 781
n@905 782 var hold = document.createElement("datetime");
n@905 783 var date = document.createElement("date");
n@905 784 date.textContent = year.nodeValue+'/'+month.nodeValue+'/'+day.nodeValue;
n@905 785 var time = document.createElement("time");
n@905 786 time.textContent = hour.nodeValue+':'+minute.nodeValue+':'+secs.nodeValue;
n@905 787
n@905 788 date.setAttributeNode(year);
n@905 789 date.setAttributeNode(month);
n@905 790 date.setAttributeNode(day);
n@905 791 time.setAttributeNode(hour);
n@905 792 time.setAttributeNode(minute);
n@905 793 time.setAttributeNode(secs);
n@905 794
n@905 795 hold.appendChild(date);
n@905 796 hold.appendChild(time);
n@905 797 return hold
n@905 798
n@905 799 }
n@905 800
n@905 801 function testWaitIndicator() {
n@905 802 if (audioEngineContext.checkAllReady() == false) {
n@905 803 var hold = document.createElement("div");
n@905 804 hold.id = "testWaitIndicator";
n@905 805 hold.className = "indicator-box";
n@905 806 var span = document.createElement("span");
n@905 807 span.textContent = "Please wait! Elements still loading";
n@905 808 hold.appendChild(span);
n@905 809 var body = document.getElementsByTagName('body')[0];
n@905 810 body.appendChild(hold);
n@905 811 testWaitTimerIntervalHolder = setInterval(function(){
n@905 812 var ready = audioEngineContext.checkAllReady();
n@905 813 if (ready) {
n@905 814 var elem = document.getElementById('testWaitIndicator');
n@905 815 var body = document.getElementsByTagName('body')[0];
n@905 816 body.removeChild(elem);
n@905 817 clearInterval(testWaitTimerIntervalHolder);
n@905 818 }
n@905 819 },500,false);
n@905 820 }
n@905 821 }
n@905 822
n@905 823 var testWaitTimerIntervalHolder = null;