Web Audio API scheduler by position

by Thanos Saringelos

JavaScript

try {
  // Fix up for prefixing
  window.AudioContext = window.AudioContext || window.webkitAudioContext;
  window.context = new AudioContext();
} catch (e) {
  alert('Web Audio API is not supported in this browser. Uninstall it now and install a descent one like Chrome or if you are already so smart just update it ! :)');
}

// global variables: tempo, MainGain which are being updated and applied often 
// other variables:
//        noteTime : is the time between 2 steps. it is calculated based on the tempo
//        startTime         : is set one time and forever, and it is the time that the sequencer started 
//        
// there is a matrix slotMatrix[i][j] which holds for every instrument for all numberOfSlots slots an instrument has

var tempo = 60;
var numberOfSlots = 64;
var numberOfInstruments = 10;
var step = 0;
var startTime;
var timeoutId;
var noteTime = 0.0;

var slotMatrix = new Array(numberOfInstruments);
for (var i = 0; i <= numberOfInstruments; i++) {
  slotMatrix[i] = new Array(numberOfSlots);
}

for (var i = 0; i <= 64; i++) {
  slotMatrix[0][i] = 1;
}

function ultimateScheduler() {

  var currentTime = window.context.currentTime;
  currentTime -= startTime;

  // enters when it is close to the next time step and has to schedule the samples accordingly    

  while (noteTime < currentTime + 0.100) {

    var contextPlayTime = noteTime + startTime;

    for (var i = 0; i <= numberOfInstruments; i++) {

      if (slotMatrix[i][step] === 1) {

        play(contextPlayTime, i);

      }


    }

    updateVars();

  }

  // by position of object
  /*
    timeRelativeNow = Math.round(currentTime * 1000) / 1000;
    var totalTime = options.properties.getPentagramProps().numOfSlots * options.properties.getPentagramProps().tempo / 60;
    var initTime = (timeRelativeNow > totalTime) ? Math.floor(timeRelativeNow / totalTime) * totalTime : 0;
    timeRelativeNow = timeRelativeNow - initTime;
    var cursorPosX =...