annotate core.js @ 909:68bc26353ada

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