-
Notifications
You must be signed in to change notification settings - Fork 10
/
client.js
90 lines (66 loc) · 2.14 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
82
83
84
85
86
87
88
89
90
const captions = window.document.getElementById("captions");
async function getMicrophone() {
const userMedia = await navigator.mediaDevices.getUserMedia({
audio: true,
});
return new MediaRecorder(userMedia);
}
async function openMicrophone(microphone, socket) {
await microphone.start(500);
microphone.onstart = () => {
console.log("client: microphone opened");
document.body.classList.add("recording");
};
microphone.onstop = () => {
console.log("client: microphone closed");
document.body.classList.remove("recording");
};
microphone.ondataavailable = (e) => {
const data = e.data;
console.log("client: sent data to websocket");
socket.send(data);
};
}
async function closeMicrophone(microphone) {
microphone.stop();
}
async function start(socket) {
const listenButton = document.getElementById("record");
let microphone;
console.log("client: waiting to open microphone");
listenButton.addEventListener("click", async () => {
if (!microphone) {
// open and close the microphone
microphone = await getMicrophone();
await openMicrophone(microphone, socket);
} else {
await closeMicrophone(microphone);
microphone = undefined;
}
});
}
async function getTempApiKey() {
const result = await fetch("/key");
const json = await result.json();
return json.key;
}
window.addEventListener("load", async () => {
const key = await getTempApiKey();
const { createClient } = deepgram;
const _deepgram = createClient(key);
const socket = _deepgram.listen.live({ model: "nova", smart_format: true });
socket.on("open", async () => {
console.log("client: connected to websocket");
socket.on("Results", (data) => {
console.log(data);
const transcript = data.channel.alternatives[0].transcript;
if (transcript !== "")
captions.innerHTML = transcript ? `<span>${transcript}</span>` : "";
});
socket.on("error", (e) => console.error(e));
socket.on("warning", (e) => console.warn(e));
socket.on("Metadata", (e) => console.log(e));
socket.on("close", (e) => console.log(e));
await start(socket);
});
});