dspjs
Version:
DSP.js is a comprehensive digital signal processing library for javascript
103 lines (81 loc) • 3.11 kB
HTML
<html>
<head>
<script language="javascript" src="js/processing.js"></script>
<script language="javascript" src="js/init.js"></script>
<script language="javascript" src="../dsp.js"></script>
</head>
<body>
<script>
// Setup shared variables
var bufferSize = 2048;
var sampleRate = 44100.0;
var sine;
var lp12;
var windowFunc;
// Setup experimental audio out
var output = new Audio();
if ( typeof output.mozSetup === 'function' ) {
output.mozSetup(1, sampleRate, 1);
}
var audioWriter = function(s) {
if ( typeof output.mozWriteAudio === 'function' ) {
output.mozWriteAudio(s);
}
}
</script>
<script target="#signal" type="application/processing">
int nthHarmonic = 1;
float frequency = 200;
void setup() {
size(1024, 600);
frameRate(60);
sine = new Oscillator(Oscillator.Sine, frequency, 1, bufferSize, sampleRate);
sine.generate();
lp12 = new IIRFilter(DSP.LOWPASS, 400, 1, sampleRate);
windowFunc = new WindowFunction(WindowFunction.Hann);
stroke(255);
strokeWeight(2);
strokeCap(SQUARE);
colorMode(HSB, 360, 100, 100);
}
void draw() {
fill(360, 0, 100, 50);
rect(-10, -10, width + 20, height + 20);
if (nthHarmonic > 40 )
{
sizes = [2048, 1024, 512, 256, 128, 512, 256, 128];
frequency = constrain(random(200), 10, 200);
bufferSize = sizes[int(random(sizes.length-1))];
nthHarmonic = 1;
sine = new Oscillator(Oscillator.Saw, frequency, 1, bufferSize, sampleRate);
sine.generate();
}
lp12 = new IIRFilter(DSP.LOWPASS, random(22050), random(5) + 1, sampleRate);
frequency = constrain((mouseX/50) * (mouseX/50), 10, 1000);
// Add harmonic
if ( nthHarmonic > 1 ) {
harmonic = new Oscillator(Oscillator.Sine, frequency*nthHarmonic, 1/nthHarmonic, bufferSize, sampleRate);
harmonic.generate();
sine.add(harmonic);
}
nthHarmonic += 2; // 3rd, 5th, 7th, 9th, etc
// Draw additive signal
for ( int i = 0; i < width - 1; i+=4 ) {
stroke((i + frameCount + 50) % 360, 100, 60);
line(i, height/2 - sine.signal[i % bufferSize] * 100, i+1, height/2 - sine.signal[(i+1) % bufferSize] * 300);
stroke((i + frameCount)% 360, 50, 100);
line(i, height/2 - sine.signal[i % bufferSize] * 200, i+1, height/2 - sine.signal[(i+1) % bufferSize] * 50);
}
noStroke();
fill(mouseX % 360, 100, 100);
rect(mouseX - 25, 0, 50, 10);
rect(mouseX - 25, height-10, 50, 10);
// Play the generated waveform
lp12.process(sine.signal);
//windowFunc.process(sine.signal);
audioWriter(sine.signal);
}
</script>
<div><canvas id="signal" width="200px" height="200px"></canvas></div>
</body>
</html>