annotate core.js @ 174:b19712875046

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