document.addEventListener("DOMContentLoaded", function() { const recordBtn = document.getElementById("record-btn"); const audioPlayer = document.getElementById("audio-player"); const chatContainer = document.getElementById("chat-container"); let mediaRecorder; let chunks = []; recordBtn.addEventListener("click", function() { if (mediaRecorder && mediaRecorder.state === "recording") { mediaRecorder.stop(); recordBtn.textContent = "Bonyeza kitufe cha kurekodi na uliza swali lako"; } else { navigator.mediaDevices.getUserMedia({ audio: true }) .then(function(stream) { mediaRecorder = new MediaRecorder(stream); chunks = []; mediaRecorder.addEventListener("dataavailable", function(e) { chunks.push(e.data); }); mediaRecorder.addEventListener("stop", function() { const audioBlob = new Blob(chunks, { type: "audio/wav" }); sendAudioToServer(audioBlob); }); mediaRecorder.start(); recordBtn.textContent = "Acha kurekodi"; }) .catch(function(err) { console.error("Error accessing microphone:", err); }); } }); function sendAudioToServer(audioBlob) { const formData = new FormData(); formData.append("audio", audioBlob, "recording.wav"); fetch("/transcribe", { method: "POST", body: formData }) .then(response => response.json()) .then(data => { const transcribedText = data.text; displayUserMessage(transcribedText); // Send the transcribed text to the server for generating a response const responseFormData = new FormData(); responseFormData.append("text", transcribedText); fetch("/generate_response", { method: "POST", body: responseFormData }) .then(response => response.json()) .then(data => { const responseText = data.response; displayAssistantMessage(responseText); // Send the response text to the server for audio inference const inferenceFormData = new FormData(); inferenceFormData.append("text", responseText); fetch("/inference", { method: "POST", body: inferenceFormData }) .then(response => response.json()) .then(data => { const audioUrl = data.audio_url; audioPlayer.src = audioUrl; audioPlayer.style.display = "block"; }); }); }); } function displayUserMessage(text) { const messageElement = document.createElement("div"); messageElement.classList.add("user-message"); messageElement.textContent = text; chatContainer.appendChild(messageElement); } function displayAssistantMessage(text) { const messageElement = document.createElement("div"); messageElement.classList.add("assistant-message"); messageElement.textContent = text; chatContainer.appendChild(messageElement); } });