-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathclient.js
81 lines (68 loc) · 2.07 KB
/
client.js
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
const captions = window.document.getElementById("captions");
async function getMicrophone() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
return new MediaRecorder(stream);
} catch (error) {
console.error("Error accessing microphone:", error);
throw error;
}
}
async function openMicrophone(microphone, socket) {
return new Promise((resolve) => {
microphone.onstart = () => {
console.log("WebSocket connection opened");
document.body.classList.add("recording");
resolve();
};
microphone.onstop = () => {
console.log("WebSocket connection closed");
document.body.classList.remove("recording");
};
microphone.ondataavailable = (event) => {
if (event.data.size > 0 && socket.readyState === WebSocket.OPEN) {
socket.send(event.data);
}
};
microphone.start(1000);
});
}
async function closeMicrophone(microphone) {
microphone.stop();
}
async function start(socket) {
const listenButton = document.querySelector("#record");
let microphone;
console.log("client: waiting to open microphone");
listenButton.addEventListener("click", async () => {
if (!microphone) {
try {
microphone = await getMicrophone();
await openMicrophone(microphone, socket);
} catch (error) {
console.error("Error opening microphone:", error);
}
} else {
await closeMicrophone(microphone);
microphone = undefined;
}
});
}
window.addEventListener("load", () => {
const socket = new WebSocket("ws://localhost:3000");
socket.addEventListener("open", async () => {
console.log("WebSocket connection opened");
await start(socket);
});
socket.addEventListener("message", (event) => {
const data = JSON.parse(event.data);
if (data.channel.alternatives[0].transcript !== "") {
captions.innerHTML = data
? `<span>${data.channel.alternatives[0].transcript}</span>`
: "";
}
});
socket.addEventListener("close", () => {
console.log("WebSocket connection closed");
});
});