JSFiddle - React, Tailwind, and code Playground
by sebpiq
HTML
<script src="https://raw.github.com/flot/flot/master/jquery.flot.js"></script>
FREQUENCIES
<div id="freq" style="width:100%;height:300px"></div>
</br>COSINE directly using the theoretical formula
<div id="signal" style="width:100%;height:300px"></div>
</br>COSINE using a phase accumulator
<div id="signal2" style="width:100%;height:300px"></div>
JavaScript
$(function() {
var sampleRate = 44100;
var signal = new Array(sampleRate);
var signal2 = new Array(sampleRate);
var freq = new Array(sampleRate);
// --- Calculating the frequencies
var y1 = 50;
var x1 = sampleRate/2;
var slope = y1/x1;
for (var i=0; i<sampleRate/2; i++) {
freq[i] = slope * i;
}
for (var i=sampleRate/2; i<sampleRate; i++) {
freq[i] = y1;
}
// --- Using the theoretical formula
for (var i=0; i<sampleRate; i++) {
signal[i] = Math.cos(freq[i] * i * 2 * Math.PI /sampleRate);
}
// --- Using a phase accumulator
var ph = 0;
for (var i=0; i<sampleRate; i++) {
ph += freq[i] * 2 * Math.PI /sampleRate
signal2[i] = Math.cos(ph);
}
// --- ploting the whole stuff
var plot;
function plotTable(elem, data) {
var plotData = [];
for (var i=0; i<data.length; i++) plotData.push([i, data[i]]);
plot = $.plot(elem,
[{ data: plotData, label: "output"}], {
series: {
lines: { show: true },
points: { show: false }
},
grid: { hoverable: true, clickable: true },
yaxis: {
min: Math.min.apply(this, data) - 1,
max: Math.max.apply(this, data) + 1
}
});
};
plotTable($("#freq"), freq);
plotTable($("#signal"), signal);
plotTable($("#signal2"), signal2);
});