<template>
  <v-container>
    <v-row>
      <label for="Audio" style="padding: 6px">Audio</label>
      <v-btn @click="recordAudio()" id="button_record">record</v-btn>
      <v-btn id="button_stop" @click="stop">stop</v-btn>
      <div id="audio" class="audio" controls></div>
    </v-row>
  </v-container>
</template>

<script>
export default {
  name: "VoiceWidget",
  data() {
    return {
      recorder: null,
    };
  },
  methods: {
    recordAudio() {
      var device = navigator.mediaDevices.getUserMedia({ audio: true });
      var items = [];
      device.then((stream) => {
        this.recorder = new MediaRecorder(stream);
        this.recorder.ondataavailable = (e) => {
          items.push(e.data);
          if (this.recorder.state === "inactive") {
            var blob = new Blob(items, { type: "audio/*" });
            var audio = document.getElementById("audio");
            var mainaudio = document.createElement("audio");
            mainaudio.setAttribute("controls", "controls");
            audio.appendChild(mainaudio);
            mainaudio.innerHTML =
              '<source src="' +
              URL.createObjectURL(blob) +
              '" type="audio/*" />';
          }
        };
        this.recorder.start();
        // I do not want a timeout to stop the recording but clicking the stop button to do so
        setTimeout(() => {
          this.recorder.stop();
        }, 5000);
      });
    },
    stop() {
      this.recorder.stop();
    },
  },
};
</script>

<style scoped></style>
