-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudio.js
More file actions
71 lines (55 loc) · 1.94 KB
/
Copy pathaudio.js
File metadata and controls
71 lines (55 loc) · 1.94 KB
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
let mediaRecorder;
let audioChunks = [];
const startBtn = document.getElementById("start");
const stopBtn = document.getElementById("stop");
const status = document.getElementById("status");
startBtn.onclick = async () => {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(stream);
audioChunks = [];
mediaRecorder.ondataavailable = e => {
if (e.data.size > 0) audioChunks.push(e.data);
};
mediaRecorder.onstop = async () => {
const blob = new Blob(audioChunks, { type: "audio/wav" });
const formData = new FormData();
formData.append("audio", blob, "input.wav");
status.textContent = "⏳ Sende Audio ans Backend...";
const res = await fetch(API_URL+"/upload-audio", {
method: "POST",
body: formData
});
const { reply } = await res.json();
status.textContent = "💬 GPT-Antwort: " + reply;
const ttsRes = await fetch(API_URL+"/tts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text: reply })
});
const ttsBlob = await ttsRes.blob();
const audioUrl = URL.createObjectURL(ttsBlob);
const audio = new Audio(audioUrl);
audio.play();
};
mediaRecorder.start();
startBtn.disabled = true;
stopBtn.disabled = false;
status.textContent = "🎙️ Aufnahme läuft...";
};
stopBtn.onclick = () => {
mediaRecorder.stop();
startBtn.disabled = false;
stopBtn.disabled = true;
status.textContent = "⏳ Verarbeitung...";
};
const chat = document.getElementById("chat");
// Nutzerfrage anzeigen (optional)
const questionMsg = document.createElement("div");
questionMsg.textContent = "🗣️ Nutzer: " + userText;
chat.appendChild(questionMsg);
// GPT-Antwort anzeigen
const answerMsg = document.createElement("div");
answerMsg.textContent = "🤖 GPT: " + reply;
chat.appendChild(answerMsg);
// automatisch runterscrollen
chat.scrollTop = chat.scrollHeight;