In this lesson I detect speech in the browser and output the resulting string to the DOM.
First I initialise the speech recognition in the browser(window.SpeechRecognition = window.SpeechRecognition || window.webkitspeechRecognition). Then create a new instance of speech recognition (new SpeechRecognition()) and start it (recognition.start()).
I then create a <p> element and .appendChild(p) to '.words'. This outputs the text spoken to the DOM element in the browser.
I listen for a 'result(e)' on 'recognition' which is where I transcribe the result into text and output that string to the browser.
In result(e) - Create a 'transcript' array from 'e.results'. Then .map() over that array to get inside of the first node that is returned (result => (.map()result[0])). Next .map() over the 'result.transcript' key and .join('') the array into one string. Then set 'p.textContent = transcript'.
Next check if the result is finished (e.results[0].isFinal). If so, create a new <p> element and append it to '.words'.
It's also possible to check if the 'transcript' contains key phrases using .includes() (transcript.includes('unicorn')).
I listen to the 'end' event on 'recognition' in-order to restart it every time the line ends ('end', recognition.start).
See the Pen
JavaScript30 - 20 - Speech Detection by Corey Noble (@CoreyNoble)
on CodePen.