Create a simple text to speech UI using JavaScript

To add a text to speech feature on your webpage using Javascript, we need to use the Web Speech API, which can be used to synthesis speech which is converting text to speech, and we can also use it to recognize speech to convert speech to text.

HTML Code:

In the HTML file, let’s set up the following elements:

<textarea class="enterText" cols="30" rows="10">Hello, Welcome to</textarea>
<button class="speakButton">Convert to speech</button>

CSS Code:

  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 1rem;
  border: 2px solid #eee;
  outline: none;
  width: 40vw;
  height: 30vh;
  padding: 1rem;
  box-shadow: 0px 1px 10px 0px rgba(0, 0, 0, 0.1);
  border: none;
  padding: 1rem;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.5s;
    background-color: rgb(200, 200, 200);

JavaScript Code:

let speak = document.querySelector(".speakButton");
speak.onclick = () => {
    let txt = document.querySelector('.enterText').value;
    let speech = new SpeechSynthesisUtterance();
    speech.lang = 'en-US';
    speech.text = txt;
    speech.rate = 1;
    speech.pitch = 1;
    speech.volume = 1;

In this tutorial we learned how to convert text to speech in your webpage using JavaScript’s Web Speech API. I hope you enjoyed this tutorial.

RH Suman
RH Suman
Articles: 64

Newsletter Updates

Enter your email address below to subscribe to our newsletter

Leave a Reply