-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.js
More file actions
169 lines (147 loc) · 5.34 KB
/
test.js
File metadata and controls
169 lines (147 loc) · 5.34 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
const bufferSize = 4096
const scroller = document.querySelector('#textDisplay')
const anchor = document.querySelector('#anchor')
const btnMic = document.querySelector("#btnMic")
const btnMicIcon = document.querySelector("#btnMicIcon")
const recordStatus = document.querySelector("#recordStatus")
const transcribeStatus = document.querySelector("#transcribeStatus")
let websocket
let context
let processor
let globalStream
let isRecording = false
// Call to initialize
function initWebSocket() {
const websocketAddress = "wss://162.157.112.2"
// const selectedLanguage = document.getElementById('languageSelect').value
language = null
websocket = new WebSocket(websocketAddress)
websocket.onopen = () => {
console.log("WebSocket connection established")
}
websocket.onclose = event => {
const transcriptionDiv = document.createElement("div")
transcriptionDiv.className = "voiceText"
transcriptionDiv.innerText = "Sorry, an error occured, please reload. If the issue persists, please reload after 5 minutes."
console.log("WebSocket connection closed", event)
}
websocket.onmessage = event => {
console.log("Message from server:", event.data)
const transcript_data = JSON.parse(event.data)
updateTranscription(transcript_data)
}
}
function updateTranscription(transcript_data) {
transcribeStatus.innerText = "Waiting"
if (transcript_data['words'] && transcript_data['words'].length > 0) {
const transcriptionDiv = document.createElement("div")
transcriptionDiv.className = "voiceText"
transcript_data['words'].forEach(wordData => {
const span = document.createElement('span')
const probability = wordData['probability']
span.textContent = wordData['word'] + ' '
if (probability > 0.6) {
span.style.color = 'black'
} else if (probability < 0.6) {
span.style.color = 'red'
}
transcriptionDiv.appendChild(span)
})
scroller.insertBefore(transcriptionDiv, anchor)
}
console.log("DEBUG: Transcription took " + transcript_data['processing_time'].toFixed(2).toString() + ' seconds.')
}
function startRecording() {
if (isRecording) return
isRecording = true
const AudioContext = window.AudioContext || window.webkitAudioContext
context = new AudioContext()
navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => {
globalStream = stream
const input = context.createMediaStreamSource(stream)
processor = context.createScriptProcessor(bufferSize, 1, 1)
processor.onaudioprocess = e => processAudio(e)
input.connect(processor)
processor.connect(context.destination)
sendAudioConfig()
}).catch(error => console.error('Error accessing microphone', error))
}
function stopRecording() {
if (!isRecording) return
isRecording = false
if (globalStream) {
globalStream.getTracks().forEach(track => track.stop())
}
if (processor) {
processor.disconnect()
processor = null
}
if (context) {
context.close().then(() => context = null)
}
}
function sendAudioConfig() {
const audioConfig = {
type: 'config',
language: language,
}
websocket.send(JSON.stringify(audioConfig))
console.log("Config Sent To Server")
}
function downsampleBuffer(buffer, inputSampleRate, outputSampleRate) {
if (inputSampleRate === outputSampleRate) {
return buffer
}
var sampleRateRatio = inputSampleRate / outputSampleRate
var newLength = Math.round(buffer.length / sampleRateRatio)
var result = new Float32Array(newLength)
var offsetResult = 0
var offsetBuffer = 0
while (offsetResult < result.length) {
var nextOffsetBuffer = Math.round((offsetResult + 1) * sampleRateRatio)
var accum = 0, count = 0
for (var i = offsetBuffer; i < nextOffsetBuffer && i < buffer.length; i++) {
accum += buffer[i]
count++
}
result[offsetResult] = accum / count
offsetResult++
offsetBuffer = nextOffsetBuffer
}
return result
}
function processAudio(e) {
const inputSampleRate = context.sampleRate
const outputSampleRate = 16000
const left = e.inputBuffer.getChannelData(0)
const downsampledBuffer = downsampleBuffer(left, inputSampleRate, outputSampleRate)
const audioData = convertFloat32ToInt16(downsampledBuffer)
if (websocket && websocket.readyState === WebSocket.OPEN) {
websocket.send(audioData)
transcribeStatus.innerText = "Transcribing"
}
}
function convertFloat32ToInt16(buffer) {
let l = buffer.length
const buf = new Int16Array(l)
while (l--) {
buf[l] = Math.min(1, buffer[l]) * 0x7FFF
}
return buf.buffer
}
btnMic.addEventListener("click", () => {
if (btnMicIcon.innerText == "mic") {
btnMicIcon.innerText = "mic_off"
recordStatus.innerText = "Muted"
stopRecording()
} else if (btnMicIcon.innerText == "mic_off") {
btnMicIcon.innerText = "mic"
recordStatus.innerText = "Recording"
startRecording()
}
})
document.addEventListener('DOMContentLoaded', () => {
console.log("Waiting for websocket")
initWebSocket()
document.querySelector("#textDisplay").scroll(0, 1)
})