generated from deepgram-starters/project-template
-
Notifications
You must be signed in to change notification settings - Fork 24
/
script.js
75 lines (67 loc) · 2.08 KB
/
script.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
let isRecording = false;
let socket;
let microphone;
const socket_port = 5001;
socket = io(
"http://" + window.location.hostname + ":" + socket_port.toString()
);
socket.on("transcription_update", (data) => {
document.getElementById("captions").innerHTML = data.transcription;
});
async function getMicrophone() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
return new MediaRecorder(stream, { mimeType: "audio/webm" });
} catch (error) {
console.error("Error accessing microphone:", error);
throw error;
}
}
async function openMicrophone(microphone, socket) {
return new Promise((resolve) => {
microphone.onstart = () => {
console.log("Client: Microphone opened");
document.body.classList.add("recording");
resolve();
};
microphone.ondataavailable = async (event) => {
console.log("client: microphone data received");
if (event.data.size > 0) {
socket.emit("audio_stream", event.data);
}
};
microphone.start(1000);
});
}
async function startRecording() {
isRecording = true;
microphone = await getMicrophone();
console.log("Client: Waiting to open microphone");
await openMicrophone(microphone, socket);
}
async function stopRecording() {
if (isRecording === true) {
microphone.stop();
microphone.stream.getTracks().forEach((track) => track.stop()); // Stop all tracks
socket.emit("toggle_transcription", { action: "stop" });
microphone = null;
isRecording = false;
console.log("Client: Microphone closed");
document.body.classList.remove("recording");
}
}
document.addEventListener("DOMContentLoaded", () => {
const recordButton = document.getElementById("record");
recordButton.addEventListener("click", () => {
if (!isRecording) {
socket.emit("toggle_transcription", { action: "start" });
startRecording().catch((error) =>
console.error("Error starting recording:", error)
);
} else {
stopRecording().catch((error) =>
console.error("Error stopping recording:", error)
);
}
});
});