// An example of jsMaxim with manual implementation of webAudio
var context = new (window.AudioContext || window.webkitAudioContext)();

var source;
var jsProcessor = 0;
var analyser;

var output = 0;
var bufferLoader;

// function handling audio processing
// called byjsProcessor
function process(event) {
    var numChannels = event.outputBuffer.numberOfChannels;
    var outputLength = event.outputBuffer.getChannelData(0).length;

    for (var i = 0; i < outputLength; ++i) {
        play();

        if(output instanceof Array){ // check if we're using arrays
            for (var channel = 0; channel < numChannels; channel++) {
                event.outputBuffer.getChannelData(channel)[i] = output[channel];
            }
        }
        else
        {
           for (var channel = 0; channel < numChannels; channel++) {
            event.outputBuffer.getChannelData(channel)[i] = output;
        }
    }
}
}

function initAudio(numChannels) {
    source = context.createBufferSource();

    jsProcessor = context.createScriptProcessor(4096, numChannels, numChannels);
    jsProcessor.onaudioprocess = process;

    analyser = context.createAnalyser();
    analyser.fftSize = 2048;

    // Connect the processing graph: source -> jsProcessor -> analyser -> destination
    source.connect(jsProcessor);
    jsProcessor.connect(analyser);
    analyser.connect(context.destination);
}

function init() {
    initAudio(2);
    setup();
}

window.onload = init;

// ----------------------------------------------------------------------
// The code

var mySine = new maximJs.maxiOsc();
var mySamp = new maximJs.maxiSample();


function setup(){
// assign sample to mySamp using current context
maximJs.maxiTools.loadSample("audio/beat2.wav", mySamp, context);
// makes temporary AudioContext to assign file
// maximJs.maxiTools.loadSample("audio/beat2.wav", mySamp); 
}

// called from process() function
function play(){
    // output = mySine.sinewave(440);

    if(mySamp.isReady()){
        output = mySamp.play();
    }
}