Skip to content

Commit

Permalink
Updated synthesizer and dsp.js
Browse files Browse the repository at this point in the history
  • Loading branch information
corbanbrook authored and Maciek416 committed May 5, 2010
1 parent feb5faf commit a3fd0ca
Show file tree
Hide file tree
Showing 2 changed files with 262 additions and 41 deletions.
40 changes: 34 additions & 6 deletions public/synth/dsp.js
Expand Up @@ -142,14 +142,16 @@ FFT.prototype.forward = function(buffer) {

return this.spectrum;
};

Oscillator = function Oscillator(type, frequency, amplitude, bufferSize, sampleRate) {
this.frequency = frequency;
this.amplitude = amplitude;
this.bufferSize = bufferSize;
this.sampleRate = sampleRate;
this.frameCount = 0;

this.waveTableLength = 2048;

this.cyclesPerSample = frequency / sampleRate;

this.signal = new Array(bufferSize);
Expand All @@ -175,9 +177,30 @@ Oscillator = function Oscillator(type, frequency, amplitude, bufferSize, sampleR
break;
}

this.generateWaveTable = function() {
Oscillator.waveTable[this.func] = Array(2048);
var waveTableTime = this.waveTableLength / this.sampleRate;
var waveTableHz = 1 / waveTableTime;

for (var i = 0; i < this.waveTableLength; i++) {
Oscillator.waveTable[this.func][i] = this.func(i * waveTableHz/this.sampleRate);
}
};

if ( typeof Oscillator.waveTable === 'undefined' ) {
Oscillator.waveTable = {};
}

if ( typeof Oscillator.waveTable[this.func] === 'undefined' ) {
this.generateWaveTable();
}

this.waveTable = Oscillator.waveTable[this.func];

//this.generate();
};


Oscillator.prototype.setAmp = function(amplitude) {
if (amplitude >= 0 && amplitude <= 1) {
this.amplitude = amplitude;
Expand Down Expand Up @@ -227,16 +250,21 @@ Oscillator.prototype.addEnvelope = function(envelope) {
};

Oscillator.prototype.valueAt = function(offset) {
return this.waveLength[offset % this.waveLength.length];
//return this.waveLength[offset % this.waveLength.length];
return this.waveTable[offset % this.waveTableLength];
};

Oscillator.prototype.generate = function() {
var frameOffset = this.frameCount * this.bufferSize, step;
var frameOffset = this.frameCount * this.bufferSize;
var step = this.waveTableLength * this.frequency / this.sampleRate;
var offset;

for ( var i = 0; i < this.bufferSize; i++ ) {
step = (frameOffset + i) * this.cyclesPerSample % 1;

this.signal[i] = this.func(step) * this.amplitude;
//var step = (frameOffset + i) * this.cyclesPerSample % 1;
//this.signal[i] = this.func(step) * this.amplitude;
//this.signal[i] = this.valueAt(Math.round((frameOffset + i) * step)) * this.amplitude;
offset = Math.round((frameOffset + i) * step);
this.signal[i] = this.waveTable[offset % this.waveTableLength] * this.amplitude;
}

this.frameCount++;
Expand Down

0 comments on commit a3fd0ca

Please sign in to comment.