DEV Community

Cover image for JavaScript-30-Day-20
KUMAR HARSH
KUMAR HARSH

Posted on • Updated on

JavaScript-30-Day-20

Native Speech Recognition

demo

Today we are going to learn all about speech recognition in the browser.

Instead of complete walk through of the project, I'll only talk about the important stuff.

Here is the complete code we write:

window.SpeechRecognition =
        window.SpeechRecognition || window.webkitSpeechRecognition;

      const recognition = new SpeechRecognition();
      recognition.interimResults = true;
      recognition.lang = "en-US";

      let p = document.createElement("p");
      const words = document.querySelector(".words");
      words.appendChild(p);

      recognition.addEventListener("result", (e) => {
        console.log(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();
Enter fullscreen mode Exit fullscreen mode

SpeechRecognition.interimResults=true;
This makes sure that results are available while we are speaking and not after we are done speaking.

We use document.createElement to create a paragraph and append it to the ‘words’ div which is a contenteditable

We add an eventListener on ‘result’ event of SpeechRecognition , In the event e, we get e.results which we assign to transcript variable.

e.results is a list, not an array and each 0th element of the list is the text data we need. So we map transcript on result[0]
Then we return transcript and join everything so that it forms a single string.

demo

This works only for one paragraph so we need to set ‘end’ event to run SpeechRecognition.start() again.

p.textContent=transcript; , We finally put transcript into DOM.

We need to run createElement and appendChild inside the result event again so that p does not get replaced in the DOM but creates a new paragraph instead.

With this we are done with the project.

GitHub repo:

Blog on Day-19 of javascript30

Blog on Day-18 of javascript30

Blog on Day-17 of javascript30

Follow me on Twitter

Follow me on Linkedin

DEV Profile

cenacr007_harsh image

You can also do the challenge at javascript30

Thanks @wesbos , WesBos to share this with us! 😊💖

Please comment and let me know your views

Thank You!

Top comments (2)

Collapse
 
rash123 profile image
RASHMI VERMA

👌👌

Collapse
 
cenacr007_harsh profile image
KUMAR HARSH

☺