Timing Test

by Ehsan Ziya

HTML

<input type="button" id="play" value="PLAY">
<input type="button" id="stop" value="STOP">

JavaScript

var context = new webkitAudioContext();

function osc(type, frequency, detune) {
    this.type = type;
    this.frequency = frequency;
    this.detune = detune;

    this.oscillator = context.createOscillator();
    this.gain = context.createGainNode();
    this.oscillator.frequency.value = frequency;
    this.oscillator.type = type;
    this.oscillator.detune.value = detune;

    this.play = function (destination, volume) {
        this.destination = destination;
        this.volume = volume;
        this.oscillator.connect(this.gain);
        this.gain.gain.value = volume;
        this.gain.connect(destination);
        this.oscillator.start(0);
    };

    this.stop = function () {
        this.oscillator.stop(0);
    };
}

function Sound(source) {

    var that = this;
    that.source = source;
    that.buffer = null;
    that.isLoaded = false;

    var request = new XMLHttpRequest();
    request.open('GET', source, true);
    request.responseType = "arraybuffer";
    request.onload = function () {
        context.decodeAudioData(request.response, function (buffer) {
            that.buffer = buffer;
            that.isLoaded = true;
        });
    };
    request.send();

    this.play = function (destination, loop, speed, gain, time) {

        if (that.isLoaded === true) {
            this.sound = context.createBufferSource();
            this.soundGain = context.createGainNode();
            this.sound.buffer = this.buffer;
            this.destination = destination;
            this.speed = speed;
            this.gain = gain;
            this.sound.loop = loop;
            this.sound.playbackRate.value = speed;
            this.soundGain.gain.value = gain;
            this.sound.connect(this.soundGain);
            this.soundGain.connect(destination);
            this.sound.start(time);
        }
    };

    this.stop = function () {
        this.sound.stop(0);
    };
}

//oscillator creation
var sine = new osc("sine", 300,...