const WaveFile = require("wavefile");
const fs = require("fs");

let wav = new WaveFile();

const MIN_FREQ = 10;
const MAX_FREQ = 160;
const SAMPLE_RATE = 44100;

const randomFreq = () => MIN_FREQ + Math.random() * (MAX_FREQ - MIN_FREQ);

const randomSlope = () => {
  const freq1 = randomFreq();
  const freq2 = Math.random() < 0.5 ? freq1 * Math.random() : freq1;
  const length = Math.round(100 + Math.random() * 5000);
  return Array(length)
    .fill(0)
    .map((x, i) => {
      const f = freq1 + (freq2 - freq1) * (i / length);
      const t = i / SAMPLE_RATE;
      return Math.sin(f * t * Math.PI * 2) * (length - i) / length;
    });
};

const randomSilence = () => {
  const length = Math.round(100 + Math.random() * 5000);
  return Array(length).fill(0);
};

const randomSong = () => {
  let samples = [];
  for (let i = 0; i < 30; i++) {
    let innerSample = []
    const a = 2 + Math.floor(Math.random() * 4)
    const b = 2 + Math.floor(Math.random() * 4)
    for (let j = 0; j < a; j++) {
      innerSample = innerSample.concat(randomSlope());
      innerSample = innerSample.concat(randomSilence());
    }
    for (let j = 0; j < b; j++) {
      samples = samples.concat(innerSample)
    }
  }
  return samples;
};

// Create a mono wave file, 44.1 kHz, 32-bit and 4 samples
wav.fromScratch(1, SAMPLE_RATE, "32f", randomSong());
fs.writeFileSync("lowend.wav", wav.toBuffer());
