File size: 5,029 Bytes
9939489
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
let audioContext;
let analyser;
let sourceNode;
let mediaRecorder;
let audioChunks = [];

document.addEventListener("DOMContentLoaded", () => {
  const audioResponseElement = document.getElementById("audioResponse");
  const micButton = document.getElementById("micButton");
  const blobs = document.querySelectorAll(".blob");

  initAudioContext(audioResponseElement);
  function initAudioContext(audioElement) {
    audioContext = new (window.AudioContext || window.webkitAudioContext)();
    analyser = audioContext.createAnalyser();
    analyser.fftSize = 64;

    if (audioElement && !sourceNode) {
      sourceNode = audioContext.createMediaElementSource(audioElement);
      sourceNode.connect(analyser);
      analyser.connect(audioContext.destination);
    }
  }

  function startWaitAnimation() {
    document.getElementById("thought-bubble").style.display = "block";

    micButton.classList.add("disabled");
    micButton.disabled = true;
  }

  function stopWaitAnimation() {
    document.getElementById("thought-bubble").style.display = "none";

    micButton.classList.remove("disabled");
    micButton.disabled = false;
  }

  function enableMicButton() {
    micButton.classList.remove("disabled");
    micButton.disabled = false;
  }

  function hideBlobs() {
    document.querySelector(".blob-container").style.display = "none";
  }

  function showBlobs() {
    document.querySelector(".blob-container").style.display = "flex";
  }

  async function startRecording() {
    audioChunks = [];
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      mediaRecorder = new MediaRecorder(stream);
      mediaRecorder.ondataavailable = (event) => audioChunks.push(event.data);
      mediaRecorder.start();
    } catch (error) {
      console.error("Error accessing audio devices:", error);
      micButton.checked = false; // Uncheck the button in case of an error
      stopWaitAnimation();
    }
  }

  function stopRecording() {
    mediaRecorder.stop();
    mediaRecorder.onstop = async () => {
      const audioBlob = new Blob(audioChunks, { type: "audio/wav" });
      const audioBase64 = await blobToBase64(audioBlob);
      sendAudioToServer(audioBase64);
    };
  }

  function blobToBase64(blob) {
    const reader = new FileReader();
    return new Promise((resolve) => {
      reader.onloadend = () => resolve(reader.result.split(",")[1]);
      reader.readAsDataURL(blob);
    });
  }
  function sendAudioToServer(audioBase64) {
    fetch(
      "https://h8v918qrvg.execute-api.eu-central-1.amazonaws.com/Prod/sts/question",
      {
        method: "POST",
        headers: { "Content-Type": "text/plain" },
        body: audioBase64,
      }
    )
      .then((response) => response.text())
      .then((data) => {
        if (data.message === "Question not provided in POST body") {
          console.error("Question not provided in POST body");
          stopWaitAnimation();
          enableMicButton(); // Re-enable the microphone button
          return; // Stop further processing
        }

        const audioSrc = `data:audio/wav;base64,${data}`;
        audioResponseElement.src = audioSrc;
        audioResponseElement.play().then(() => {
          visualize(); // Start the visualizer after the audio starts playing
        });
      })
      .catch((error) => {
        console.error("Error:", error);
        stopWaitAnimation();
      });
  }

  micButton.addEventListener("change", () => {
    hideBlobs();
    if (micButton.checked) {
      startRecording();
    } else {
      stopRecording();
      startWaitAnimation();
    }
  });

  function visualize() {
    if (!audioContext) {
      console.error("AudioContext not initialized");
      return;
    }

    if (!sourceNode) {
      console.error("SourceNode not initialized");
      return;
    }
    const bufferLength = analyser.frequencyBinCount;
    const dataArray = new Uint8Array(bufferLength);

    function draw() {
      requestAnimationFrame(draw);
      analyser.getByteFrequencyData(dataArray);

      const segmentLength = Math.floor(bufferLength / blobs.length);
      for (let i = 0; i < blobs.length; i++) {
        // Use an average value of a segment of the dataArray for each blob
        const dataValue = dataArray[(i * segmentLength) / 2] || 0;
        // Fallback to 0 if undefined
        const height = (dataValue / 128.0) * 50 + 50;

        blobs[i].style.height = `${height}px`;
      }
    }

    draw();
  }

  audioResponseElement.onended = () => {
    hideBlobs(); // Hide the blobs once the audio has finished playing
    stopWaitAnimation();
    enableMicButton(); // Ensure thought bubble is not showing
  };

  audioResponseElement.onplay = () => {
    showBlobs(); // Show the blobs when audio starts playing
    stopWaitAnimation(); // Hide the thought bubble when audio starts playing
  };

  document.body.addEventListener("click", () => {
    if (audioContext && audioContext.state === "suspended") {
      audioContext.resume();
    }
  });
});