-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
60 lines (47 loc) · 1.75 KB
/
app.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
// Create new instance - speech synthesis
const synthesis = window.speechSynthesis;
// Establish that browser has speech recognition
window.SpeechRecognition =
window.SpeechRecognition || window.webkitSpeechRecognition;
// Create new instance - speech recognition
const recognition = new SpeechRecognition();
recognition.interimResults = true;
recognition.continuous = true;
recognition.lang = 'en-US';
// Grab elements from the DOM
let startRecognition = document.querySelector('#start');
let stopRecognition = document.querySelector('#stop');
let clearTranscript = document.querySelector('#clear');
let playSpeech = document.querySelector('#play');
let transcript = document.querySelector('#transcript');
// Add event listeners
startRecognition.addEventListener('click', handleStartRecognition);
stopRecognition.addEventListener('click', handleStopRecognition);
clearTranscript.addEventListener('click', handleClearTranscript);
playSpeech.addEventListener('click', handlePlaySpeech);
function handleStartRecognition(event) {
console.log('start speech recognition');
recognition.addEventListener('error', (event) => {
console.log('an error occurred');
});
recognition.addEventListener('result', (event) => {
const results = Array.from(event.results)
.map((item) => item[0].transcript)
.join('');
console.log(results);
transcript.textContent = results;
});
recognition.start();
}
function handleStopRecognition(event) {
console.log('stop speech recognition');
recognition.stop();
}
function handleClearTranscript(event) {
transcript.textContent = '';
}
function handlePlaySpeech(event) {
console.log('speech synthesis');
let utterance = new SpeechSynthesisUtterance(transcript.textContent);
synthesis.speak(utterance);
}