<script>

const startButton = <button type="button">start</button>
const stopButton = <button type="button">stop</button>
const playButton = <button type="button">play</button>

const ui = <div> 
  {startButton}
  {stopButton}
  {playButton}
</div>

class AudioRecorder {
  constructor() {
    this.mediaRecorder = null;
    this.audioChunks = [];
    this.stream = null;
    this.lastAudioUrl = null; // Store the URL of the last recording
  }

  async init() {
    try {
      this.stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      this.mediaRecorder = new MediaRecorder(this.stream);
      this.setupListeners();
    } catch (error) {
      console.error("Error accessing the microphone:", error);
    }
  }

  setupListeners() {
    this.mediaRecorder.addEventListener("dataavailable", event => {
      this.audioChunks.push(event.data);
    });

    this.mediaRecorder.addEventListener("stop", () => {
      const audioBlob = new Blob(this.audioChunks);
      if (this.lastAudioUrl) {
        // Revoke the old URL to avoid memory leaks
        URL.revokeObjectURL(this.lastAudioUrl);
      }
      this.lastAudioUrl = URL.createObjectURL(audioBlob);
      this.cleanup(); // Cleanup the audio chunks for the next recording
    });
  }

  startRecording() {
    if (this.mediaRecorder && this.mediaRecorder.state === "inactive") {
      this.audioChunks = []; // Clear previous recordings
      this.mediaRecorder.start();
      console.log("Recording started");
    } else {
      console.log("Recorder not initialized or already recording");
    }
  }

  stopRecording() {
    if (this.mediaRecorder && this.mediaRecorder.state === "recording") {
      this.mediaRecorder.stop();
      console.log("Recording stopped");
    } else {
      console.log("Recorder not started or already stopped");
    }
  }

  play() {
    if (this.lastAudioUrl) {
      const audio = new Audio(this.lastAudioUrl);
      audio.play();
      console.log("Playback started");
    } else {
      console.log("No recording available to play");
    }
  }

  cleanup() {
    if (this.stream) {
      this.stream.getTracks().forEach(track => track.stop());
    }
    this.audioChunks = [];
    console.log("Cleanup done, stream tracks stopped");
  }
}

// Example usage:
const recorder = new AudioRecorder();

startButton.addEventListener("click", () => recorder.startRecording());
stopButton.addEventListener("click", () => recorder.stopRecording());
playButton.addEventListener("click", () => recorder.play());

ui

</script>

