Skip to content

Commit

Permalink
data: normalize before/after noise
Browse files Browse the repository at this point in the history
  • Loading branch information
indutny committed Oct 24, 2020
1 parent 3e42a4a commit f4cfca4
Showing 1 changed file with 15 additions and 11 deletions.
26 changes: 15 additions & 11 deletions src/data.mjs
Expand Up @@ -10,6 +10,17 @@ export default class Data {
this.fftOut = this.fft.createComplexArray();
}

normalize(list) {
let max = 0;
for (let i = 0; i < list.length; i++) {
max = Math.max(max, Math.abs(list[i]));
}

for (let i = 0; i < list.length; i++) {
list[i] /= max;
}
}

sample(freq) {
// E6=1318
// A1=55
Expand All @@ -19,32 +30,25 @@ export default class Data {
const f = freq / this.sampleRate;
const phase = Math.random();
const harmonicFade = 0.25 + 0.25 * Math.random();
const noise = Math.random() * 0.3;

let norm = 0;
for (let h = 0; h < 3; h++) {
norm += Math.pow(harmonicFade, h);
}

this.fftIn.fill(0);
let max = 0;
for (let t = 0; t < this.fftIn.length; t++) {
let signal = 0;

for (let h = 0; h < 3; h++) {
signal += Math.sin(2 * Math.PI * (Math.pow(2, h) * f * t + phase)) *
Math.pow(harmonicFade, h);
}
signal /= norm;

signal = signal * (1 - noise) + Math.random() * noise;
max = Math.max(max, Math.abs(signal));
this.fftIn[t] = signal;
}
this.normalize(this.fftIn);

const noise = Math.random() * 0.3;
for (let t = 0; t < this.fftIn.length; t++) {
this.fftIn[t] /= max;
this.fftIn[t] = this.fftIn[t] * (1 - noise) + Math.random() * noise;
}
this.normalize(this.fftIn);

this.fft.realTransform(this.fftOut, this.fftIn);

Expand Down

0 comments on commit f4cfca4

Please sign in to comment.