This is a JavaScript practice with JavaScript30 by Wes Bos without any frameworks, no compilers, no boilerplate, and no libraries.
view demo here
window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
const recognition = new SpeechRecognition();
recognition.interimResults = true;
-
window.SpeechRecognition
is aWeb Speech API
. -
recognition.interimResults = true;
makes sure that results are available while we are speaking
let p = document.createElement('p');
const words = document.querySelector('.words');
words.appendChild(p);
- use
document.createElement
to create a paragraph andappend
it to the.words
div
recognition.addEventListener('result', e => {
const transcript = Array.from(e.results)
.map(result => result[0])
.map(result => result.transcript)
.join('');
const poopScript = transcript.replace(/poop|poo|shit|dump/gi, '💩');
p.textContent = poopScript;
if (e.results[0].isFinal) {
p = document.createElement('p');
words.appendChild(p);
}
});
recognition.addEventListener('end', recognition.start);
recognition.start();
-
add an
eventListener
onresult
event of SpeechRecognition, in the event we will gete.results
and assign to thetranscript
variable. -
e.results
is a list NOT an array -
each
0th
element of the list is the text data we need, so we have tomap
transcript onresult[0]
-
return
transcript
andjoin
everything so that it forms a single string. -
this only works for one paragraph so we need to set
recognition.addEventListener('end', recognition.start)
again -
to avoid the
<p>
get replaced in the DOM, we need to runcreateElement
andappendChild
inside theresult
event again so that it creates a new paragraph instead.