annotate core.js @ 926:f427b5805b69

Merge in main
author Nicholas Jillings <nicholas.jillings@eecs.qmul.ac.uk>
date Sat, 30 May 2015 11:39:53 +0100
parents
children c19c4b0b00fd
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);
nicholas@926 206 this.stateResults.push(obj);
nicholas@926 207 }
nicholas@926 208 } else {
nicholas@926 209 conolse.log('FATAL - StateMap not correctly constructed. EMPTY_STATE_MAP');
nicholas@926 210 }
nicholas@926 211 };
nicholas@926 212 this.advanceState = function(){
nicholas@926 213 if (this.stateIndex == null) {
nicholas@926 214 this.initialise();
nicholas@926 215 }
nicholas@926 216 if (this.stateIndex == -1) {
nicholas@926 217 console.log('Starting test...');
nicholas@926 218 }
nicholas@926 219 if (this.currentIndex == null){
nicholas@926 220 if (this.currentStateMap.nodeName == "audioHolder") {
nicholas@926 221 // Save current page
nicholas@926 222 this.testPageCompleted(this.stateResults[this.stateIndex],this.currentStateMap,this.currentTestId);
nicholas@926 223 this.currentTestId++;
nicholas@926 224 }
nicholas@926 225 this.stateIndex++;
nicholas@926 226 if (this.stateIndex >= this.stateMap.length) {
nicholas@926 227 console.log('Test Completed');
nicholas@926 228 createProjectSave(projectReturn);
nicholas@926 229 } else {
nicholas@926 230 this.currentStateMap = this.stateMap[this.stateIndex];
nicholas@926 231 if (this.currentStateMap.nodeName == "audioHolder") {
nicholas@926 232 console.log('Loading test page');
nicholas@926 233 loadTest(this.currentStateMap);
nicholas@926 234 this.initialiseInnerState(this.currentStateMap);
nicholas@926 235 } else if (this.currentStateMap.nodeName == "PreTest" || this.currentStateMap.nodeName == "PostTest") {
nicholas@926 236 if (this.currentStateMap.childElementCount >= 1) {
nicholas@926 237 popup.initState(this.currentStateMap);
nicholas@926 238 } else {
nicholas@926 239 this.advanceState();
nicholas@926 240 }
nicholas@926 241 } else {
nicholas@926 242 this.advanceState();
nicholas@926 243 }
nicholas@926 244 }
nicholas@926 245 } else {
nicholas@926 246 this.advanceInnerState();
nicholas@926 247 }
nicholas@926 248 };
nicholas@926 249
nicholas@926 250 this.testPageCompleted = function(store, testXML, testId) {
nicholas@926 251 // Function called each time a test page has been completed
nicholas@926 252 // Can be used to over-rule default behaviour
nicholas@926 253
nicholas@926 254 pageXMLSave(store, testXML, testId);
nicholas@926 255 }
nicholas@926 256
nicholas@926 257 this.initialiseInnerState = function(testXML) {
nicholas@926 258 // Parses the received testXML for pre and post test options
nicholas@926 259 this.currentStateMap = [];
nicholas@926 260 var preTest = $(testXML).find('PreTest')[0];
nicholas@926 261 var postTest = $(testXML).find('PostTest')[0];
nicholas@926 262 if (preTest == undefined) {preTest = document.createElement("preTest");}
nicholas@926 263 if (postTest == undefined){postTest= document.createElement("postTest");}
nicholas@926 264 this.currentStateMap.push(preTest);
nicholas@926 265 this.currentStateMap.push(testXML);
nicholas@926 266 this.currentStateMap.push(postTest);
nicholas@926 267 this.currentIndex = -1;
nicholas@926 268 this.advanceInnerState();
nicholas@926 269 }
nicholas@926 270
nicholas@926 271 this.advanceInnerState = function() {
nicholas@926 272 this.currentIndex++;
nicholas@926 273 if (this.currentIndex >= this.currentStateMap.length) {
nicholas@926 274 this.currentIndex = null;
nicholas@926 275 this.currentStateMap = this.stateMap[this.stateIndex];
nicholas@926 276 this.advanceState();
nicholas@926 277 } else {
nicholas@926 278 if (this.currentStateMap[this.currentIndex].nodeName == "audioHolder") {
nicholas@926 279 console.log("Loading test page"+this.currentTestId);
nicholas@926 280 } else if (this.currentStateMap[this.currentIndex].nodeName == "PreTest") {
nicholas@926 281 popup.initState(this.currentStateMap[this.currentIndex]);
nicholas@926 282 } else if (this.currentStateMap[this.currentIndex].nodeName == "PostTest") {
nicholas@926 283 popup.initState(this.currentStateMap[this.currentIndex]);
nicholas@926 284 } else {
nicholas@926 285 this.advanceInnerState();
nicholas@926 286 }
nicholas@926 287 }
nicholas@926 288 }
nicholas@926 289
nicholas@926 290 this.previousState = function(){};
nicholas@926 291 }
nicholas@926 292
nicholas@926 293 function testEnded(testId)
nicholas@926 294 {
nicholas@926 295 pageXMLSave(testId);
nicholas@926 296 if (testXMLSetups.length-1 > testId)
nicholas@926 297 {
nicholas@926 298 // Yes we have another test to perform
nicholas@926 299 testId = (Number(testId)+1);
nicholas@926 300 currentState = 'testRun-'+testId;
nicholas@926 301 loadTest(testId);
nicholas@926 302 } else {
nicholas@926 303 console.log('Testing Completed!');
nicholas@926 304 currentState = 'postTest';
nicholas@926 305 // Check for any post tests
nicholas@926 306 var xmlSetup = projectXML.find('setup');
nicholas@926 307 var postTest = xmlSetup.find('PostTest')[0];
nicholas@926 308 popup.initState(postTest);
nicholas@926 309 }
nicholas@926 310 }
nicholas@926 311
nicholas@926 312 function loadProjectSpec(url) {
nicholas@926 313 // Load the project document from the given URL, decode the XML and instruct audioEngine to get audio data
nicholas@926 314 // If url is null, request client to upload project XML document
nicholas@926 315 var r = new XMLHttpRequest();
nicholas@926 316 r.open('GET',url,true);
nicholas@926 317 r.onload = function() {
nicholas@926 318 loadProjectSpecCallback(r.response);
nicholas@926 319 };
nicholas@926 320 r.send();
nicholas@926 321 };
nicholas@926 322
nicholas@926 323 function loadProjectSpecCallback(response) {
nicholas@926 324 // Function called after asynchronous download of XML project specification
nicholas@926 325 var decode = $.parseXML(response);
nicholas@926 326 projectXML = $(decode);
nicholas@926 327
nicholas@926 328 // Now extract the setup tag
nicholas@926 329 var xmlSetup = projectXML.find('setup');
nicholas@926 330 // Detect the interface to use and load the relevant javascripts.
nicholas@926 331 var interfaceType = xmlSetup[0].attributes['interface'];
nicholas@926 332 var interfaceJS = document.createElement('script');
nicholas@926 333 interfaceJS.setAttribute("type","text/javascript");
nicholas@926 334 if (interfaceType.value == 'APE') {
nicholas@926 335 interfaceJS.setAttribute("src","ape.js");
nicholas@926 336
nicholas@926 337 // APE comes with a css file
nicholas@926 338 var css = document.createElement('link');
nicholas@926 339 css.rel = 'stylesheet';
nicholas@926 340 css.type = 'text/css';
nicholas@926 341 css.href = 'ape.css';
nicholas@926 342
nicholas@926 343 document.getElementsByTagName("head")[0].appendChild(css);
nicholas@926 344 }
nicholas@926 345 document.getElementsByTagName("head")[0].appendChild(interfaceJS);
nicholas@926 346
nicholas@926 347 // Define window callbacks for interface
nicholas@926 348 window.onresize = function(event){resizeWindow(event);};
nicholas@926 349 }
nicholas@926 350
nicholas@926 351 function createProjectSave(destURL) {
nicholas@926 352 // Save the data from interface into XML and send to destURL
nicholas@926 353 // If destURL is null then download XML in client
nicholas@926 354 // Now time to render file locally
nicholas@926 355 var xmlDoc = interfaceXMLSave();
nicholas@926 356 var parent = document.createElement("div");
nicholas@926 357 parent.appendChild(xmlDoc);
nicholas@926 358 var file = [parent.innerHTML];
nicholas@926 359 if (destURL == "null" || destURL == undefined) {
nicholas@926 360 var bb = new Blob(file,{type : 'application/xml'});
nicholas@926 361 var dnlk = window.URL.createObjectURL(bb);
nicholas@926 362 var a = document.createElement("a");
nicholas@926 363 a.hidden = '';
nicholas@926 364 a.href = dnlk;
nicholas@926 365 a.download = "save.xml";
nicholas@926 366 a.textContent = "Save File";
nicholas@926 367
nicholas@926 368 var submitDiv = document.getElementById('download-point');
nicholas@926 369 submitDiv.appendChild(a);
nicholas@926 370 popup.showPopup();
nicholas@926 371 popup.popupContent.innerHTML = null;
nicholas@926 372 popup.popupContent.appendChild(submitDiv)
nicholas@926 373 } else {
nicholas@926 374 var xmlhttp = new XMLHttpRequest;
nicholas@926 375 xmlhttp.open("POST",destURL,true);
nicholas@926 376 xmlhttp.setRequestHeader('Content-Type', 'text/xml');
nicholas@926 377 xmlhttp.onerror = function(){
nicholas@926 378 console.log('Error saving file to server! Presenting download locally');
nicholas@926 379 createProjectSave(null);
nicholas@926 380 };
nicholas@926 381 xmlhttp.send(file);
nicholas@926 382 }
nicholas@926 383 return submitDiv;
nicholas@926 384 }
nicholas@926 385
nicholas@926 386 // Only other global function which must be defined in the interface class. Determines how to create the XML document.
nicholas@926 387 function interfaceXMLSave(){
nicholas@926 388 // Create the XML string to be exported with results
nicholas@926 389 var xmlDoc = document.createElement("BrowserEvaluationResult");
nicholas@926 390 xmlDoc.appendChild(returnDateNode());
nicholas@926 391 for (var i=0; i<testState.stateResults.length; i++)
nicholas@926 392 {
nicholas@926 393 xmlDoc.appendChild(testState.stateResults[i]);
nicholas@926 394 }
nicholas@926 395
nicholas@926 396 return xmlDoc;
nicholas@926 397 }
nicholas@926 398
nicholas@926 399 function AudioEngine() {
nicholas@926 400
nicholas@926 401 // Create two output paths, the main outputGain and fooGain.
nicholas@926 402 // Output gain is default to 1 and any items for playback route here
nicholas@926 403 // Foo gain is used for analysis to ensure paths get processed, but are not heard
nicholas@926 404 // because web audio will optimise and any route which does not go to the destination gets ignored.
nicholas@926 405 this.outputGain = audioContext.createGain();
nicholas@926 406 this.fooGain = audioContext.createGain();
nicholas@926 407 this.fooGain.gain = 0;
nicholas@926 408
nicholas@926 409 // Use this to detect playback state: 0 - stopped, 1 - playing
nicholas@926 410 this.status = 0;
nicholas@926 411 this.audioObjectsReady = false;
nicholas@926 412
nicholas@926 413 // Connect both gains to output
nicholas@926 414 this.outputGain.connect(audioContext.destination);
nicholas@926 415 this.fooGain.connect(audioContext.destination);
nicholas@926 416
nicholas@926 417 // Create the timer Object
nicholas@926 418 this.timer = new timer();
nicholas@926 419 // Create session metrics
nicholas@926 420 this.metric = new sessionMetrics(this);
nicholas@926 421
nicholas@926 422 this.loopPlayback = false;
nicholas@926 423
nicholas@926 424 // Create store for new audioObjects
nicholas@926 425 this.audioObjects = [];
nicholas@926 426
nicholas@926 427 this.play = function() {
nicholas@926 428 // Start the timer and set the audioEngine state to playing (1)
nicholas@926 429 if (this.status == 0) {
nicholas@926 430 // Check if all audioObjects are ready
nicholas@926 431 if (this.audioObjectsReady == false) {
nicholas@926 432 this.audioObjectsReady = this.checkAllReady();
nicholas@926 433 }
nicholas@926 434 if (this.audioObjectsReady == true) {
nicholas@926 435 this.timer.startTest();
nicholas@926 436 if (this.loopPlayback) {
nicholas@926 437 for(var i=0; i<this.audioObjects.length; i++) {
nicholas@926 438 this.audioObjects[i].play(this.timer.getTestTime()+1);
nicholas@926 439 }
nicholas@926 440 }
nicholas@926 441 this.status = 1;
nicholas@926 442 }
nicholas@926 443 }
nicholas@926 444 };
nicholas@926 445
nicholas@926 446 this.stop = function() {
nicholas@926 447 // Send stop and reset command to all playback buffers and set audioEngine state to stopped (1)
nicholas@926 448 if (this.status == 1) {
nicholas@926 449 for (var i=0; i<this.audioObjects.length; i++)
nicholas@926 450 {
nicholas@926 451 this.audioObjects[i].stop();
nicholas@926 452 }
nicholas@926 453 this.status = 0;
nicholas@926 454 }
nicholas@926 455 };
nicholas@926 456
nicholas@926 457
nicholas@926 458 this.newTrack = function(url) {
nicholas@926 459 // Pull data from given URL into new audio buffer
nicholas@926 460 // URLs must either be from the same source OR be setup to 'Access-Control-Allow-Origin'
nicholas@926 461
nicholas@926 462 // Create the audioObject with ID of the new track length;
nicholas@926 463 audioObjectId = this.audioObjects.length;
nicholas@926 464 this.audioObjects[audioObjectId] = new audioObject(audioObjectId);
nicholas@926 465
nicholas@926 466 // AudioObject will get track itself.
nicholas@926 467 this.audioObjects[audioObjectId].constructTrack(url);
nicholas@926 468 };
nicholas@926 469
nicholas@926 470 this.newTestPage = function() {
nicholas@926 471 this.state = 0;
nicholas@926 472 this.audioObjectsReady = false;
nicholas@926 473 this.metric.reset();
nicholas@926 474 this.audioObjects = [];
nicholas@926 475 };
nicholas@926 476
nicholas@926 477 this.checkAllPlayed = function() {
nicholas@926 478 arr = [];
nicholas@926 479 for (var id=0; id<this.audioObjects.length; id++) {
nicholas@926 480 if (this.audioObjects[id].metric.wasListenedTo == false) {
nicholas@926 481 arr.push(this.audioObjects[id].id);
nicholas@926 482 }
nicholas@926 483 }
nicholas@926 484 return arr;
nicholas@926 485 };
nicholas@926 486
nicholas@926 487 this.checkAllReady = function() {
nicholas@926 488 var ready = true;
nicholas@926 489 for (var i=0; i<this.audioObjects.length; i++) {
nicholas@926 490 if (this.audioObjects[i].state == 0) {
nicholas@926 491 // Track not ready
nicholas@926 492 console.log('WAIT -- audioObject '+i+' not ready yet!');
nicholas@926 493 ready = false;
nicholas@926 494 };
nicholas@926 495 }
nicholas@926 496 if (ready == false) {
nicholas@926 497 var holder = document.getElementById('testWaitIndicator');
nicholas@926 498 holder.style.visibility = "visible";
nicholas@926 499 setInterval(function() {
nicholas@926 500 document.getElementById('testWaitIndicator').style.visibility = "hidden";
nicholas@926 501 }, 10000);
nicholas@926 502 }
nicholas@926 503 return ready;
nicholas@926 504 };
nicholas@926 505
nicholas@926 506 }
nicholas@926 507
nicholas@926 508 function audioObject(id) {
nicholas@926 509 // The main buffer object with common control nodes to the AudioEngine
nicholas@926 510
nicholas@926 511 this.id = id;
nicholas@926 512 this.state = 0; // 0 - no data, 1 - ready
nicholas@926 513 this.url = null; // Hold the URL given for the output back to the results.
nicholas@926 514 this.metric = new metricTracker(this);
nicholas@926 515
nicholas@926 516 // Create a buffer and external gain control to allow internal patching of effects and volume leveling.
nicholas@926 517 this.bufferNode = undefined;
nicholas@926 518 this.outputGain = audioContext.createGain();
nicholas@926 519
nicholas@926 520 // Default output gain to be zero
nicholas@926 521 this.outputGain.gain.value = 0.0;
nicholas@926 522
nicholas@926 523 // Connect buffer to the audio graph
nicholas@926 524 this.outputGain.connect(audioEngineContext.outputGain);
nicholas@926 525
nicholas@926 526 // the audiobuffer is not designed for multi-start playback
nicholas@926 527 // When stopeed, the buffer node is deleted and recreated with the stored buffer.
nicholas@926 528 this.buffer;
nicholas@926 529
nicholas@926 530 this.loopStart = function() {
nicholas@926 531 this.outputGain.gain.value = 1.0;
nicholas@926 532 this.metric.startListening(audioEngineContext.timer.getTestTime());
nicholas@926 533 }
nicholas@926 534
nicholas@926 535 this.loopStop = function() {
nicholas@926 536 if (this.outputGain.gain.value != 0.0) {
nicholas@926 537 this.outputGain.gain.value = 0.0;
nicholas@926 538 this.metric.stopListening(audioEngineContext.timer.getTestTime());
nicholas@926 539 }
nicholas@926 540 }
nicholas@926 541
nicholas@926 542 this.play = function(startTime) {
nicholas@926 543 this.bufferNode = audioContext.createBufferSource();
nicholas@926 544 this.bufferNode.owner = this;
nicholas@926 545 this.bufferNode.connect(this.outputGain);
nicholas@926 546 this.bufferNode.buffer = this.buffer;
nicholas@926 547 this.bufferNode.loop = audioEngineContext.loopPlayback;
nicholas@926 548 this.bufferNode.onended = function() {
nicholas@926 549 // Safari does not like using 'this' to reference the calling object!
nicholas@926 550 event.srcElement.owner.metric.stopListening(audioEngineContext.timer.getTestTime());
nicholas@926 551 };
nicholas@926 552 if (this.bufferNode.loop == false) {
nicholas@926 553 this.metric.startListening(audioEngineContext.timer.getTestTime());
nicholas@926 554 }
nicholas@926 555 this.bufferNode.start(startTime);
nicholas@926 556 };
nicholas@926 557
nicholas@926 558 this.stop = function() {
nicholas@926 559 if (this.bufferNode != undefined)
nicholas@926 560 {
nicholas@926 561 this.bufferNode.stop(0);
nicholas@926 562 this.bufferNode = undefined;
nicholas@926 563 this.metric.stopListening(audioEngineContext.timer.getTestTime());
nicholas@926 564 }
nicholas@926 565 };
nicholas@926 566
nicholas@926 567 this.constructTrack = function(url) {
nicholas@926 568 var request = new XMLHttpRequest();
nicholas@926 569 this.url = url;
nicholas@926 570 request.open('GET',url,true);
nicholas@926 571 request.responseType = 'arraybuffer';
nicholas@926 572
nicholas@926 573 var audioObj = this;
nicholas@926 574
nicholas@926 575 // Create callback to decode the data asynchronously
nicholas@926 576 request.onloadend = function() {
nicholas@926 577 audioContext.decodeAudioData(request.response, function(decodedData) {
nicholas@926 578 audioObj.buffer = decodedData;
nicholas@926 579 audioObj.state = 1;
nicholas@926 580 }, function(){
nicholas@926 581 // Should only be called if there was an error, but sometimes gets called continuously
nicholas@926 582 // Check here if the error is genuine
nicholas@926 583 if (audioObj.state == 0 || audioObj.buffer == undefined) {
nicholas@926 584 // Genuine error
nicholas@926 585 console.log('FATAL - Error loading buffer on '+audioObj.id);
nicholas@926 586 }
nicholas@926 587 });
nicholas@926 588 };
nicholas@926 589 request.send();
nicholas@926 590 };
nicholas@926 591
nicholas@926 592 }
nicholas@926 593
nicholas@926 594 function timer()
nicholas@926 595 {
nicholas@926 596 /* Timer object used in audioEngine to keep track of session timings
nicholas@926 597 * Uses the timer of the web audio API, so sample resolution
nicholas@926 598 */
nicholas@926 599 this.testStarted = false;
nicholas@926 600 this.testStartTime = 0;
nicholas@926 601 this.testDuration = 0;
nicholas@926 602 this.minimumTestTime = 0; // No minimum test time
nicholas@926 603 this.startTest = function()
nicholas@926 604 {
nicholas@926 605 if (this.testStarted == false)
nicholas@926 606 {
nicholas@926 607 this.testStartTime = audioContext.currentTime;
nicholas@926 608 this.testStarted = true;
nicholas@926 609 this.updateTestTime();
nicholas@926 610 audioEngineContext.metric.initialiseTest();
nicholas@926 611 }
nicholas@926 612 };
nicholas@926 613 this.stopTest = function()
nicholas@926 614 {
nicholas@926 615 if (this.testStarted)
nicholas@926 616 {
nicholas@926 617 this.testDuration = this.getTestTime();
nicholas@926 618 this.testStarted = false;
nicholas@926 619 } else {
nicholas@926 620 console.log('ERR: Test tried to end before beginning');
nicholas@926 621 }
nicholas@926 622 };
nicholas@926 623 this.updateTestTime = function()
nicholas@926 624 {
nicholas@926 625 if (this.testStarted)
nicholas@926 626 {
nicholas@926 627 this.testDuration = audioContext.currentTime - this.testStartTime;
nicholas@926 628 }
nicholas@926 629 };
nicholas@926 630 this.getTestTime = function()
nicholas@926 631 {
nicholas@926 632 this.updateTestTime();
nicholas@926 633 return this.testDuration;
nicholas@926 634 };
nicholas@926 635 }
nicholas@926 636
nicholas@926 637 function sessionMetrics(engine)
nicholas@926 638 {
nicholas@926 639 /* Used by audioEngine to link to audioObjects to minimise the timer call timers;
nicholas@926 640 */
nicholas@926 641 this.engine = engine;
nicholas@926 642 this.lastClicked = -1;
nicholas@926 643 this.data = -1;
nicholas@926 644 this.reset = function() {
nicholas@926 645 this.lastClicked = -1;
nicholas@926 646 this.data = -1;
nicholas@926 647 };
nicholas@926 648 this.initialiseTest = function(){};
nicholas@926 649 }
nicholas@926 650
nicholas@926 651 function metricTracker(caller)
nicholas@926 652 {
nicholas@926 653 /* Custom object to track and collect metric data
nicholas@926 654 * Used only inside the audioObjects object.
nicholas@926 655 */
nicholas@926 656
nicholas@926 657 this.listenedTimer = 0;
nicholas@926 658 this.listenStart = 0;
nicholas@926 659 this.listenHold = false;
nicholas@926 660 this.initialPosition = -1;
nicholas@926 661 this.movementTracker = [];
nicholas@926 662 this.wasListenedTo = false;
nicholas@926 663 this.wasMoved = false;
nicholas@926 664 this.hasComments = false;
nicholas@926 665 this.parent = caller;
nicholas@926 666
nicholas@926 667 this.initialised = function(position)
nicholas@926 668 {
nicholas@926 669 if (this.initialPosition == -1) {
nicholas@926 670 this.initialPosition = position;
nicholas@926 671 }
nicholas@926 672 };
nicholas@926 673
nicholas@926 674 this.moved = function(time,position)
nicholas@926 675 {
nicholas@926 676 this.wasMoved = true;
nicholas@926 677 this.movementTracker[this.movementTracker.length] = [time, position];
nicholas@926 678 };
nicholas@926 679
nicholas@926 680 this.startListening = function(time)
nicholas@926 681 {
nicholas@926 682 if (this.listenHold == false)
nicholas@926 683 {
nicholas@926 684 this.wasListenedTo = true;
nicholas@926 685 this.listenStart = time;
nicholas@926 686 this.listenHold = true;
nicholas@926 687 console.log('slider ' + this.parent.id + ' played (' + time + ')'); // DEBUG/SAFETY: show played slider id
nicholas@926 688 }
nicholas@926 689 };
nicholas@926 690
nicholas@926 691 this.stopListening = function(time)
nicholas@926 692 {
nicholas@926 693 if (this.listenHold == true)
nicholas@926 694 {
nicholas@926 695 this.listenedTimer += (time - this.listenStart);
nicholas@926 696 this.listenStart = 0;
nicholas@926 697 this.listenHold = false;
nicholas@926 698 }
nicholas@926 699 };
nicholas@926 700 }
nicholas@926 701
nicholas@926 702 function randomiseOrder(input)
nicholas@926 703 {
nicholas@926 704 // This takes an array of information and randomises the order
nicholas@926 705 var N = input.length;
nicholas@926 706 var K = N;
nicholas@926 707 var holdArr = [];
nicholas@926 708 for (var n=0; n<N; n++)
nicholas@926 709 {
nicholas@926 710 // First pick a random number
nicholas@926 711 var r = Math.random();
nicholas@926 712 // Multiply and floor by the number of elements left
nicholas@926 713 r = Math.floor(r*input.length);
nicholas@926 714 // Pick out that element and delete from the array
nicholas@926 715 holdArr.push(input.splice(r,1)[0]);
nicholas@926 716 }
nicholas@926 717 return holdArr;
nicholas@926 718 }
nicholas@926 719
nicholas@926 720 function returnDateNode()
nicholas@926 721 {
nicholas@926 722 // Create an XML Node for the Date and Time a test was conducted
nicholas@926 723 // Structure is
nicholas@926 724 // <datetime>
nicholas@926 725 // <date year="##" month="##" day="##">DD/MM/YY</date>
nicholas@926 726 // <time hour="##" minute="##" sec="##">HH:MM:SS</time>
nicholas@926 727 // </datetime>
nicholas@926 728 var dateTime = new Date();
nicholas@926 729 var year = document.createAttribute('year');
nicholas@926 730 var month = document.createAttribute('month');
nicholas@926 731 var day = document.createAttribute('day');
nicholas@926 732 var hour = document.createAttribute('hour');
nicholas@926 733 var minute = document.createAttribute('minute');
nicholas@926 734 var secs = document.createAttribute('secs');
nicholas@926 735
nicholas@926 736 year.nodeValue = dateTime.getFullYear();
nicholas@926 737 month.nodeValue = dateTime.getMonth()+1;
nicholas@926 738 day.nodeValue = dateTime.getDate();
nicholas@926 739 hour.nodeValue = dateTime.getHours();
nicholas@926 740 minute.nodeValue = dateTime.getMinutes();
nicholas@926 741 secs.nodeValue = dateTime.getSeconds();
nicholas@926 742
nicholas@926 743 var hold = document.createElement("datetime");
nicholas@926 744 var date = document.createElement("date");
nicholas@926 745 date.textContent = year.nodeValue+'/'+month.nodeValue+'/'+day.nodeValue;
nicholas@926 746 var time = document.createElement("time");
nicholas@926 747 time.textContent = hour.nodeValue+':'+minute.nodeValue+':'+secs.nodeValue;
nicholas@926 748
nicholas@926 749 date.setAttributeNode(year);
nicholas@926 750 date.setAttributeNode(month);
nicholas@926 751 date.setAttributeNode(day);
nicholas@926 752 time.setAttributeNode(hour);
nicholas@926 753 time.setAttributeNode(minute);
nicholas@926 754 time.setAttributeNode(secs);
nicholas@926 755
nicholas@926 756 hold.appendChild(date);
nicholas@926 757 hold.appendChild(time);
nicholas@926 758 return hold
nicholas@926 759
nicholas@926 760 }
nicholas@926 761
nicholas@926 762 function testWaitIndicator() {
nicholas@926 763 var hold = document.createElement("div");
nicholas@926 764 hold.id = "testWaitIndicator";
nicholas@926 765 hold.style.position = "absolute";
nicholas@926 766 hold.style.left = "100px";
nicholas@926 767 hold.style.top = "10px";
nicholas@926 768 hold.style.width = "500px";
nicholas@926 769 hold.style.height = "100px";
nicholas@926 770 hold.style.padding = "20px";
nicholas@926 771 hold.style.backgroundColor = "rgb(100,200,200)";
nicholas@926 772 hold.style.visibility = "hidden";
nicholas@926 773 var span = document.createElement("span");
nicholas@926 774 span.textContent = "Please wait! Elements still loading";
nicholas@926 775 hold.appendChild(span);
nicholas@926 776 var body = document.getElementsByTagName('body')[0];
nicholas@926 777 body.appendChild(hold);
nicholas@926 778 }
nicholas@926 779
nicholas@926 780 var hidetestwait = null;