annotate core.js @ 930:c19c4b0b00fd

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