<template>
  <div>
        <div class="container">
            <h1 class="display-4">{{ text }}</h1>
        </div>
  </div>
</template>
<script>
export default {
  mounted() {
    let audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    let upperPercentile = 0.9;
    let lowerPercentile = 0.1;
    let buffer = [];
    let levelValues = [];
    let upperValue = 0;
    let lowerValue = 0;

    navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {
      let source = audioCtx.createMediaStreamSource(stream);

      let bandPass65 = audioCtx.createBiquadFilter();
      bandPass65.type = "bandpass";
      bandPass65.frequency.value = 65;
      bandPass65.Q.value = 1.41;

      let bandPass125 = audioCtx.createBiquadFilter();
      bandPass125.type = "bandpass";
      bandPass125.frequency.value = 125;
      bandPass125.Q.value = 1.41;

      let analyser = audioCtx.createAnalyser();
      analyser.fftSize = 512;
      analyser.minDecibels = -100;
      analyser.maxDecibels = -1;

      source.connect(bandPass65);
      bandPass65.connect(bandPass125);
      bandPass125.connect(analyser);

      let dataArray = new Float32Array(analyser.frequencyBinCount);

      function update() {
        analyser.getFloatFrequencyData(dataArray);
        buffer.push(...dataArray);
        if (buffer.length > 10 * audioCtx.sampleRate) {
          buffer = buffer.slice(-10 * audioCtx.sampleRate);
        }

        levelValues = buffer.map(val => Math.pow(10, (val / 20)));
        levelValues = levelValues.map(val => Math.floor(val));

        let sortedData = levelValues.slice().sort((a, b) => a - b);
        upperValue = sortedData[Math.floor(upperPercentile * sortedData.length)];
        lowerValue = sortedData[Math.floor(lowerPercentile * sortedData.length)];

        console.log("Upper Percentile in Decimal: " + upperValue);


        console.log("Lower Percentile in Decimal: " + lowerValue);
        requestAnimationFrame(update);
      }

      update();
    });
    },
  data(){
      return{
        text : "Helo World",
      }
    }
}
</script>