<template>
  <div>
    <button @click="startRecording">Start Recording</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      audioContext: null,
      audioStream: null,
      audioInput: null,
      bufferSize: 512,
      sampleRate: 44100,
      recording: false,
      samples: []
    };
  },
  methods: {
    startRecording() {
      navigator.mediaDevices.getUserMedia({ audio: true })
          .then(stream => {
            this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
            this.audioStream = stream;
            this.audioInput = this.audioContext.createMediaStreamSource(stream);

            const analyser = this.audioContext.createAnalyser();
            analyser.fftSize = this.bufferSize * 2;
            const bufferLength = analyser.frequencyBinCount;
            const dataArray = new Float32Array(bufferLength);

            this.audioInput.connect(analyser);

            const requiredSamples = Math.round(this.sampleRate * 0.125);
            let totalSamples = 0;

            const captureInterval = setInterval(() => {
              analyser.getFloatTimeDomainData(dataArray);
              this.samples.push(...dataArray);
              totalSamples += bufferLength;

              if (totalSamples >= requiredSamples) {
                if (this.samples.length >= this.sampleRate * 5) {
                  // this.samples = this.samples.slice(0, this.sampleRate * 5);
                console.log(this.samples.length);
                  clearInterval(captureInterval);
                  this.stopRecording();
                }
              }
            }, 1000 / (this.sampleRate / this.bufferSize));
          })
          .catch(error => {
            console.error('Error accessing microphone:', error);
          });
    },
    stopRecording() {
      this.recording = false;
      this.audioInput.disconnect();
      this.audioStream.getTracks()[0].stop();
      this.audioContext.close();
      console.log('Samples:', this.samples);
    }
  }
};
</script>
