<script>

const startButton = <button type="button">start</button>
const stopButton = <button type="button">stop</button>
const playButton = <button type="button">play</button>
const transcriptButton = <button> transcribe</button>
import OpenAI from "https://lively-kernel.org/lively4/lively4-core/demos/openai/openai.js";
const key = await OpenAI.ensureSubscriptionKey();
const url =  "https://api.openai.com/v1/audio/transcriptions";

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

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

  async init() {
      this.stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      this.mediaRecorder = new MediaRecorder(this.stream);
      this.setupListeners();
  }

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

    this.mediaRecorder.addEventListener("stop", () => {
      const audioBlob = new Blob(this.audioChunks);
      this.lastBlob = audioBlob;
      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();
    }
  }

  stopRecording() {
    if (this.mediaRecorder && this.mediaRecorder.state === "recording") {
      this.mediaRecorder.stop();
      }
  }

  play() {
    if (this.lastAudioUrl) {
      const audio = new Audio(this.lastAudioUrl);
      audio.play();
    }
  }

  cleanup() {
    if (this.stream) {
      this.stream.getTracks().forEach(track => track.stop());
    }
    this.audioChunks = [];
  }
}




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


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

ui

</script>
