Building A Text To Speech Converter For Beginners!
Tags: javascript, beginners, tutorial, opensource
Published: 2021-11-24 15:28:58

Hey everyone! Today we’ll be building something just too awesome in this article, you will learn how to create a Text To Speech Converter with HTML, CSS, and JavaScript.

I have worked very hard on this project to make it come true, all that for not even a single penny 😍. Do stargaze and support this project at the official repository for this project on <a href="https://github.com/RoyalityFreeWebHosting/TextToSpeech">GitHub</a> and a demo is available <a href="https://royalityfree.com/opensource/TextToSpeech/">here</a>!<img src="https://www.gstatic.com/bricks/image/8ebd398d2db3f7da5bbd1a36ecfd8cb9cf41265d5250d5279fea0ac41823c4c6.svg" alt="Text To Speech"/><figcaption>How Cloud Speech Works (Source: Google)</figcaption>

## What Is Text To Speech Converter In The First Place? (Core Basics)

Text To Speech (TTS) is a technology that empowers your text to be converted into speech verbal sounds.

In this project (Text To Speech Converter), you can convert your text into speech with different voices and accents powered by native output methods for every type of device.

A pause and resume button that is embedded into the core of your text is above the minimum requirement of ~125 words/characters.

## About The Text To Speech Converter Project (Understanding Basics)

In the JavaScript code, originally, I got the user text and call a function <code>textToSpeech()</code> with parsing the user input text as an argument.

Inside this function, leveraging the speech synthesis property of the window object, I converted the user input text to speech.

Speech Synthesis is defined as a web speech API that moderates the speech service using native speech verbal’s available on the base device.
After this, I got all the available verbal voices from the user device using the <code>getVoices()</code> scheme of Speech Synthesis and insert it into the attributed HTML select tag. </p>

That’s all and I request you to continue reading to get more knowledge depth on what the code is actually performing.

<div class="wp-block-image"><figure class="aligncenter"><img src="https://sugermint.com/wp-content/uploads/2021/06/text-to-speech-software.jpg" alt="Best Text To Speech Software For Voice Over &amp; Youtube Videos (USA 2021) - Text  To Speech Converter"/><figcaption>Source: SugarMint</figcaption></figure></div>

## Building Text To Speech Converter Project (Free Source Code 🎉)

To build this Text To Speech Converter project, you need to create three core files, namely a <code><strong>.html</strong></code>, <code><strong>.css</strong></code> and a <code><strong>.js</strong></code> file. After organizing these files just paste the given codes into your file.

You can further download the source code files of this Text To Speech Project from the proffered download button below at the end of this article.

Firstly, create an HTML file with a filename of <code><strong>index.html</strong></code> and paste the following codes into your HTML file. <strong>Save It</strong>, you’ve to create a file with an <code><strong>.html</strong></code> extension at the last.
```
<!doctype html>
<html lang="en">
  <head>
<!-- Built By RoyalityFree's Blog-->
    <meta charset="utf-8">
    <title>Text To Speech | RoyalityFree Codes</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css" integrity="sha512-YWzhKL2whUzgiheMoBFwW8CKV4qpHQAEuvilg9FAn5VJUDwKZZxkJNuGM4XkWuk94WCrrwslk8yWNGmY1EduTA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <link rel="stylesheet" href="assets/style.css">
  </head>
  <body>
    <div class="wrapper">
     <div class="container-fluid">
      <h2 class="h2 text-center">
          Text To Speech
      </h2>
      <form>
        <div class="form-group row">
          <label class="col-sm- col-form-label">Enter Text <span class="badge badge-success">Max 5000 Letters</span>
          </label>
          <div class="col-15">
              <textarea maxlength="5000"></textarea>
        </div>
        </div>
        <div class="form-group row">
            <label>Select Voice</label>
            <div class="outer">
              <select></select>
            </div>
        </div>
        <div class="form-group row">
          <div class="col-15">
            <button type="submit" class="btn btn-primary">Convert To Speech</button>
          </div>
        </div>
      </form>
     </div>
    </div>
    <script src="script.js"></script>
  </body>
</html>
```
Secondly, create a CSS file with the filename of <code><strong>style.css</strong></code> and paste the following code in the file. <strong>Save It</strong>, you have to create a file with <strong><code>.css</code></strong> extension at the last.
```
/* Built By RoyalityFree's Blog | Codes */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
} /*Applied Universally*/

body{
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background-image: linear-gradient(90deg, #1d4aff, #829bff,#1d4aff);
}

::selection{
  color: #fff;
  background: #5256AD; /* Change Selection Colour*/
}

.wrapper{
  width: 370px;
  padding: 25px 30px;
  border-radius: 7px;
  background: #fff;
  box-shadow: 7px 7px 20px rgba(0,0,0,0.05);
} /*Box Behind*/

.wrapper header{
  font-size: 28px;
  font-weight: 500;
  text-align: center;
}

.wrapper form{
  margin: 35px 0 20px;
}

form .row{
  display: flex;
  margin-bottom: 20px;
  flex-direction: column;
}

form .row label{
  font-size: 18px;
  margin-bottom: 5px;
}

form .row:nth-child(2) label{
  font-size: 17px;
}

form :where(textarea, select, button){
  outline: none;
  width: 100%;
  height: 100%;
  border: none;
  border-radius: 5px;
}

form .row textarea{
  resize: none;
  height: 110px;
  font-size: 15px;
  padding: 8px 10px;
  border: 1px solid #999;
}

form .row textarea::-webkit-scrollbar{
  width: 0px;
}

form .row .outer{
  height: 47px;
  display: flex;
  padding: 0 10px;
  align-items: center;
  border-radius: 5px;
  justify-content: center;
  border: 1px solid #999;
}

form .row select{
  font-size: 14px;
  background: none;
}

form .row select::-webkit-scrollbar{
  width: 8px;
}

form .row select::-webkit-scrollbar-track{
  background: #fff;
}

form .row select::-webkit-scrollbar-thumb{
  background: #888;
  border-radius: 8px;
  border-right: 2px solid #ffffff;
}

form button{
  height: 52px;
  color: #fff;
  font-size: 17px;
  cursor: pointer;
  margin-top: 10px;
  background: #675AFE;
  transition: 0.3s ease;
}

form button:hover{
  background: #4534fe;
}

@media(max-width: 728px){
  .wrapper{
    max-width: 345px;
    width: 100%;
    margin-left: 7px;
    margin-right: 7px;
  }
} /*For Mobile View*/
```

Finally, create a JavaScript file with a filename of <strong><code>script.js</code></strong> and paste the following code in your JavaScript file. <strong>Save It</strong>, you have to create a file with <strong><code>.js</code></strong> extension at last.

```
const textarea = document.querySelector("textarea"),
voiceList = document.querySelector("select"), // Selection
speechBtn = document.querySelector("button");

let synth = speechSynthesis,
isSpeaking = true;

voices();

function voices(){
    for(let voice of synth.getVoices()){
        let selected = voice.name === "Google US English" ? "selected" : "";
        let option = `<option value="${voice.name}" ${selected}>${voice.name} (${voice.lang})</option>`;
        voiceList.insertAdjacentHTML("beforeend", option); // Getting Verbal's 
    }
}

synth.addEventListener("voiceschanged", voices);

function textToSpeech(text){
    let utterance = new SpeechSynthesisUtterance(text);
    for(let voice of synth.getVoices()){
        if(voice.name === voiceList.value){
            utterance.voice = voice;
        }
    }
    synth.speak(utterance);
}

speechBtn.addEventListener("click", e =>{
    e.preventDefault();
    if(textarea.value !== ""){
        if(!synth.speaking){
            textToSpeech(textarea.value);
        }
        if(textarea.value.length > 80){
            setInterval(()=>{
                if(!synth.speaking && !isSpeaking){
                    isSpeaking = true;
                    speechBtn.innerText = "Convert To Speech"; //Execute
                }else{
                }
            }, 500);
            if(isSpeaking){
                synth.resume();
                isSpeaking = false;
                speechBtn.innerText = "Pause Speech"; //Pause
            }else{
                synth.pause();
                isSpeaking = true;
                speechBtn.innerText = "Resume Speech"; //Resume
            }
        }else{
            speechBtn.innerText = "Convert To Speech"; //Execute
        }
    }
});
```
<!-- wp:image {"align":"center"} -->
<div class="wp-block-image"><figure class="aligncenter"><img src="https://voximplant.com/assets/images/2020/05/28/text-to-speech-api-scheme-3.jpg" alt="How auto Text-to-Speech works?"/><figcaption>Source: VoximPlant</figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:heading -->
<h2>Text To Speech  Converter (Last Words)</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>That’s it, you’ve now successfully built a Text To Speech Converter Project in native HTML, CSS, and JavaScript. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If your code does not work or you have faced any problem/issue, try downloading the source files from the provided download button below. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>It’s priceless and a <strong><code>.zip</code></strong> file will be downloaded and then just extract it to your filemanager, server, etc.</p>
<!-- /wp:paragraph -->

<!-- wp:html -->
<center><a href="https://gplinks.co/text-to-speech"><img src="https://i.imgur.com/6MyzmJa.png?1"></a></center>
<!-- /wp:html -->