annotate core.js @ 1608:a21deccefe7d

Currently playing sample red.
author Brecht De Man <b.deman@qmul.ac.uk>
date Sat, 16 May 2015 17:52:51 +0100
parents
children 759c2ace3c65 f378fb8286ae
rev   line source
b@1608 1 /**
b@1608 2 * core.js
b@1608 3 *
b@1608 4 * Main script to run, calls all other core functions and manages loading/store to backend.
b@1608 5 * Also contains all global variables.
b@1608 6 */
b@1608 7
b@1608 8 /* create the web audio API context and store in audioContext*/
b@1608 9 var audioContext; // Hold the browser web audio API
b@1608 10 var projectXML; // Hold the parsed setup XML
b@1608 11
b@1608 12 var testXMLSetups = []; // Hold the parsed test instances
b@1608 13 var testResultsHolders =[]; // Hold the results from each test for publishing to XML
b@1608 14 var currentTrackOrder = []; // Hold the current XML tracks in their (randomised) order
b@1608 15 var currentTestHolder; // Hold any intermediate results during test - metrics
b@1608 16 var audioEngineContext; // The custome AudioEngine object
b@1608 17 var projectReturn; // Hold the URL for the return
b@1608 18 var preTestQuestions = document.createElement('PreTest'); // Store any pre-test question response
b@1608 19 var postTestQuestions = document.createElement('PostTest'); // Store any post-test question response
b@1608 20
b@1608 21 // Add a prototype to the bufferSourceNode to reference to the audioObject holding it
b@1608 22 AudioBufferSourceNode.prototype.owner = undefined;
b@1608 23
b@1608 24 window.onload = function() {
b@1608 25 // Function called once the browser has loaded all files.
b@1608 26 // This should perform any initial commands such as structure / loading documents
b@1608 27
b@1608 28 // Create a web audio API context
b@1608 29 // Fixed for cross-browser support
b@1608 30 var AudioContext = window.AudioContext || window.webkitAudioContext;
b@1608 31 audioContext = new AudioContext;
b@1608 32
b@1608 33 // Create the audio engine object
b@1608 34 audioEngineContext = new AudioEngine();
b@1608 35 };
b@1608 36
b@1608 37 function loadProjectSpec(url) {
b@1608 38 // Load the project document from the given URL, decode the XML and instruct audioEngine to get audio data
b@1608 39 // If url is null, request client to upload project XML document
b@1608 40 var r = new XMLHttpRequest();
b@1608 41 r.open('GET',url,true);
b@1608 42 r.onload = function() {
b@1608 43 loadProjectSpecCallback(r.response);
b@1608 44 };
b@1608 45 r.send();
b@1608 46 };
b@1608 47
b@1608 48 function loadProjectSpecCallback(response) {
b@1608 49 // Function called after asynchronous download of XML project specification
b@1608 50 var decode = $.parseXML(response);
b@1608 51 projectXML = $(decode);
b@1608 52
b@1608 53 // Now extract the setup tag
b@1608 54 var xmlSetup = projectXML.find('setup');
b@1608 55 // Detect the interface to use and load the relevant javascripts.
b@1608 56 var interfaceType = xmlSetup[0].attributes['interface'];
b@1608 57 var interfaceJS = document.createElement('script');
b@1608 58 interfaceJS.setAttribute("type","text/javascript");
b@1608 59 if (interfaceType.value == 'APE') {
b@1608 60 interfaceJS.setAttribute("src","ape.js");
b@1608 61
b@1608 62 // APE comes with a css file
b@1608 63 var css = document.createElement('link');
b@1608 64 css.rel = 'stylesheet';
b@1608 65 css.type = 'text/css';
b@1608 66 css.href = 'ape.css';
b@1608 67
b@1608 68 document.getElementsByTagName("head")[0].appendChild(css);
b@1608 69 }
b@1608 70 document.getElementsByTagName("head")[0].appendChild(interfaceJS);
b@1608 71 }
b@1608 72
b@1608 73 function createProjectSave(destURL) {
b@1608 74 // Save the data from interface into XML and send to destURL
b@1608 75 // If destURL is null then download XML in client
b@1608 76 // Now time to render file locally
b@1608 77 var xmlDoc = interfaceXMLSave();
b@1608 78 if (destURL == "null" || destURL == undefined) {
b@1608 79 var parent = document.createElement("div");
b@1608 80 parent.appendChild(xmlDoc);
b@1608 81 var file = [parent.innerHTML];
b@1608 82 var bb = new Blob(file,{type : 'application/xml'});
b@1608 83 var dnlk = window.URL.createObjectURL(bb);
b@1608 84 var a = document.createElement("a");
b@1608 85 a.hidden = '';
b@1608 86 a.href = dnlk;
b@1608 87 a.download = "save.xml";
b@1608 88 a.textContent = "Save File";
b@1608 89
b@1608 90 var submitDiv = document.getElementById('download-point');
b@1608 91 submitDiv.appendChild(a);
b@1608 92 }
b@1608 93 return submitDiv;
b@1608 94 }
b@1608 95
b@1608 96 function AudioEngine() {
b@1608 97
b@1608 98 // Create two output paths, the main outputGain and fooGain.
b@1608 99 // Output gain is default to 1 and any items for playback route here
b@1608 100 // Foo gain is used for analysis to ensure paths get processed, but are not heard
b@1608 101 // because web audio will optimise and any route which does not go to the destination gets ignored.
b@1608 102 this.outputGain = audioContext.createGain();
b@1608 103 this.fooGain = audioContext.createGain();
b@1608 104 this.fooGain.gain = 0;
b@1608 105
b@1608 106 // Use this to detect playback state: 0 - stopped, 1 - playing
b@1608 107 this.status = 0;
b@1608 108
b@1608 109 // Connect both gains to output
b@1608 110 this.outputGain.connect(audioContext.destination);
b@1608 111 this.fooGain.connect(audioContext.destination);
b@1608 112
b@1608 113 // Create the timer Object
b@1608 114 this.timer = new timer();
b@1608 115 // Create session metrics
b@1608 116 this.metric = new sessionMetrics(this);
b@1608 117
b@1608 118 this.loopPlayback = false;
b@1608 119
b@1608 120 // Create store for new audioObjects
b@1608 121 this.audioObjects = [];
b@1608 122
b@1608 123 this.play = function(){};
b@1608 124
b@1608 125 this.stop = function(){};
b@1608 126
b@1608 127
b@1608 128 this.newTrack = function(url) {
b@1608 129 // Pull data from given URL into new audio buffer
b@1608 130 // URLs must either be from the same source OR be setup to 'Access-Control-Allow-Origin'
b@1608 131
b@1608 132 // Create the audioObject with ID of the new track length;
b@1608 133 audioObjectId = this.audioObjects.length;
b@1608 134 this.audioObjects[audioObjectId] = new audioObject(audioObjectId);
b@1608 135
b@1608 136 // AudioObject will get track itself.
b@1608 137 this.audioObjects[audioObjectId].constructTrack(url);
b@1608 138 };
b@1608 139
b@1608 140 }
b@1608 141
b@1608 142 function audioObject(id) {
b@1608 143 // The main buffer object with common control nodes to the AudioEngine
b@1608 144
b@1608 145 this.id = id;
b@1608 146 this.state = 0; // 0 - no data, 1 - ready
b@1608 147 this.url = null; // Hold the URL given for the output back to the results.
b@1608 148 this.metric = new metricTracker();
b@1608 149
b@1608 150 // Create a buffer and external gain control to allow internal patching of effects and volume leveling.
b@1608 151 this.bufferNode = undefined;
b@1608 152 this.outputGain = audioContext.createGain();
b@1608 153
b@1608 154 // Default output gain to be zero
b@1608 155 this.outputGain.gain.value = 0.0;
b@1608 156
b@1608 157 // Connect buffer to the audio graph
b@1608 158 this.outputGain.connect(audioEngineContext.outputGain);
b@1608 159
b@1608 160 // the audiobuffer is not designed for multi-start playback
b@1608 161 // When stopeed, the buffer node is deleted and recreated with the stored buffer.
b@1608 162 this.buffer;
b@1608 163
b@1608 164 this.play = function(startTime) {
b@1608 165 this.bufferNode = audioContext.createBufferSource();
b@1608 166 this.bufferNode.connect(this.outputGain);
b@1608 167 this.bufferNode.buffer = this.buffer;
b@1608 168 this.bufferNode.loop = audioEngineContext.loopPlayback;
b@1608 169 this.bufferNode.start(startTime);
b@1608 170 };
b@1608 171
b@1608 172 this.stop = function() {
b@1608 173 this.bufferNode.stop(0);
b@1608 174 this.bufferNode = undefined;
b@1608 175 };
b@1608 176
b@1608 177 this.constructTrack = function(url) {
b@1608 178 var request = new XMLHttpRequest();
b@1608 179 this.url = url;
b@1608 180 request.open('GET',url,true);
b@1608 181 request.responseType = 'arraybuffer';
b@1608 182
b@1608 183 var audioObj = this;
b@1608 184
b@1608 185 // Create callback to decode the data asynchronously
b@1608 186 request.onloadend = function() {
b@1608 187 audioContext.decodeAudioData(request.response, function(decodedData) {
b@1608 188 audioObj.buffer = decodedData;
b@1608 189 audioObj.state = 1;
b@1608 190 }, function(){
b@1608 191 // Should only be called if there was an error, but sometimes gets called continuously
b@1608 192 // Check here if the error is genuine
b@1608 193 if (audioObj.state == 0 || audioObj.buffer == undefined) {
b@1608 194 // Genuine error
b@1608 195 console.log('FATAL - Error loading buffer on '+audioObj.id);
b@1608 196 }
b@1608 197 });
b@1608 198 };
b@1608 199 request.send();
b@1608 200 };
b@1608 201
b@1608 202 }
b@1608 203
b@1608 204 function timer()
b@1608 205 {
b@1608 206 /* Timer object used in audioEngine to keep track of session timings
b@1608 207 * Uses the timer of the web audio API, so sample resolution
b@1608 208 */
b@1608 209 this.testStarted = false;
b@1608 210 this.testStartTime = 0;
b@1608 211 this.testDuration = 0;
b@1608 212 this.minimumTestTime = 0; // No minimum test time
b@1608 213 this.startTest = function()
b@1608 214 {
b@1608 215 if (this.testStarted == false)
b@1608 216 {
b@1608 217 this.testStartTime = audioContext.currentTime;
b@1608 218 this.testStarted = true;
b@1608 219 this.updateTestTime();
b@1608 220 audioEngineContext.metric.initialiseTest();
b@1608 221 }
b@1608 222 };
b@1608 223 this.stopTest = function()
b@1608 224 {
b@1608 225 if (this.testStarted)
b@1608 226 {
b@1608 227 this.testDuration = this.getTestTime();
b@1608 228 this.testStarted = false;
b@1608 229 } else {
b@1608 230 console.log('ERR: Test tried to end before beginning');
b@1608 231 }
b@1608 232 };
b@1608 233 this.updateTestTime = function()
b@1608 234 {
b@1608 235 if (this.testStarted)
b@1608 236 {
b@1608 237 this.testDuration = audioContext.currentTime - this.testStartTime;
b@1608 238 }
b@1608 239 };
b@1608 240 this.getTestTime = function()
b@1608 241 {
b@1608 242 this.updateTestTime();
b@1608 243 return this.testDuration;
b@1608 244 };
b@1608 245 }
b@1608 246
b@1608 247 function sessionMetrics(engine)
b@1608 248 {
b@1608 249 /* Used by audioEngine to link to audioObjects to minimise the timer call timers;
b@1608 250 */
b@1608 251 this.engine = engine;
b@1608 252 this.lastClicked = -1;
b@1608 253 this.data = -1;
b@1608 254 this.initialiseTest = function(){};
b@1608 255 }
b@1608 256
b@1608 257 function metricTracker()
b@1608 258 {
b@1608 259 /* Custom object to track and collect metric data
b@1608 260 * Used only inside the audioObjects object.
b@1608 261 */
b@1608 262
b@1608 263 this.listenedTimer = 0;
b@1608 264 this.listenStart = 0;
b@1608 265 this.initialPosition = -1;
b@1608 266 this.movementTracker = [];
b@1608 267 this.wasListenedTo = false;
b@1608 268 this.wasMoved = false;
b@1608 269 this.hasComments = false;
b@1608 270
b@1608 271 this.initialised = function(position)
b@1608 272 {
b@1608 273 if (this.initialPosition == -1) {
b@1608 274 this.initialPosition = position;
b@1608 275 }
b@1608 276 };
b@1608 277
b@1608 278 this.moved = function(time,position)
b@1608 279 {
b@1608 280 this.wasMoved = true;
b@1608 281 this.movementTracker[this.movementTracker.length] = [time, position];
b@1608 282 };
b@1608 283
b@1608 284 this.listening = function(time)
b@1608 285 {
b@1608 286 if (this.listenStart == 0)
b@1608 287 {
b@1608 288 this.wasListenedTo = true;
b@1608 289 this.listenStart = time;
b@1608 290 } else {
b@1608 291 this.listenedTimer += (time - this.listenStart);
b@1608 292 this.listenStart = 0;
b@1608 293 }
b@1608 294 };
b@1608 295 }
b@1608 296
b@1608 297 function randomiseOrder(input)
b@1608 298 {
b@1608 299 // This takes an array of information and randomises the order
b@1608 300 var N = input.length;
b@1608 301 var K = N;
b@1608 302 var holdArr = [];
b@1608 303 for (var n=0; n<N; n++)
b@1608 304 {
b@1608 305 // First pick a random number
b@1608 306 var r = Math.random();
b@1608 307 // Multiply and floor by the number of elements left
b@1608 308 r = Math.floor(r*input.length);
b@1608 309 // Pick out that element and delete from the array
b@1608 310 holdArr.push(input.splice(r,1)[0]);
b@1608 311 }
b@1608 312 return holdArr;
b@1608 313 }