<template>
  <div>
    <button @click="startMicrophone">Start Microphone</button>
    <button @click="stopMicrophone">Stop Microphone</button>
    <div v-if="errorMessage">{{ errorMessage }}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      audioContext: null,
      microphoneStream: null,
      audioProcessorNode: null,
      errorMessage: null,
    };
  },
  methods: {
    async startMicrophone() {

        this.audioContext = new window.AudioContext ();

        // Request access to the microphone
        this.microphoneStream = await navigator.mediaDevices.getUserMedia({ audio: true });

        // Check if the microphone stream is available
        if (!this.microphoneStream) {
          console.error("Microphone stream is not available.");
          this.errorMessage = "Microphone stream is not available.";
          return;
        }

        // Ensure that the microphoneStream is a MediaStream object
        if (!(this.microphoneStream instanceof MediaStream)) {
          console.error("Invalid microphone stream.");
          this.errorMessage = "Invalid microphone stream.";
          return;
        }

        // Create a MediaStreamAudioSourceNode from the microphone stream
        const microphoneSource = this.audioContext.createMediaStreamSource(this.microphoneStream);
        await this.audioContext.audioWorklet.addModule('@/plugins/octave.js');
        this.audioProcessorNode = new AudioWorkletNode(this.audioContext, 'octave');
        microphoneSource.connect(this.audioProcessorNode);
        this.audioProcessorNode.connect(this.audioContext.destination);
        // Try to add the Audio Worklet module

    },
    stopMicrophone() {
      if (this.audioContext) {
        // Disconnect and close the AudioWorkletNode
        if (this.audioProcessorNode) {
          this.audioProcessorNode.disconnect();
          this.audioProcessorNode.port.postMessage({ command: 'stop' });
        }

        // Close the AudioContext
        this.audioContext.close();

        // Reset variables
        this.audioContext = null;
        this.microphoneStream = null;
        this.audioProcessorNode = null;
        this.errorMessage = null;
      }
    },
  },
};
</script>
