-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathaudioHandler.js
75 lines (70 loc) · 2.66 KB
/
audioHandler.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
const speechRecognitionConstructor = window.SpeechRecognition || window.webkitSpeechRecognition;
const textBox = document.querySelector("#textContainer");
if(speechRecognitionConstructor){
//The browser has native support for speech recognition
let speechRecognition = null;
document.querySelector("#voiceRecorder").addEventListener("click", function() {
if(!speechRecognition){
this.classList.add("loading");
textBox.focus();
speechRecognition = new webkitSpeechRecognition();
speechRecognition.onresult = (e) => {
textBox.value = "";
for(const result of e.results){
console.log(result[0].transcript);
if(result.isFinal){
textBox.value += result[0].transcript;
this.classList.remove("loading");
}
}
};
speechRecognition.continuous = true;
//Shows on intermediate results..
speechRecognition.interimResults = true;
speechRecognition.start();
}else{
speechRecognition.stop();
speechRecognition = null;
this.classList.remove("loading");
textBox.blur();
}
});
}else{
let recorder = null, gumStream = null;
document.querySelector("#voiceRecorder").addEventListener("click", function() {
if(!recorder){
this.classList.add("loading");
navigator.mediaDevices.getUserMedia({
audio: true,
video: false
}).then(function(stream) {
let context = new AudioContext();
gumStream = stream;
let input = context.createMediaStreamSource(stream);
recorder = new Recorder(input, {
numberOfChannels: 1,
numChannels: 1
});
recorder.record();
});
}else{
recorder.stop();
gumStream.getAudioTracks()[0].stop();
recorder.exportWAV(handleGeneratedAudioFile.bind(this));
}
});
function handleGeneratedAudioFile(blob) {
fetch("https://cors-anywhere.herokuapp.com/https://api.wit.ai/speech?v=20200513", {
body: blob,
headers: {
"Authorization": "Bearer 3POVIIRNYZNAWPWS2J4LHHLUZXTTLGIU",
"Content-Type": "audio/wav"
},
method: "POST"
}).then(resp => resp.json())
.then(resp => {
textBox.value = resp.text
this.classList.remove("loading");
})
}
}