DEV Community

RoyalityFree
RoyalityFree

Posted on • Originally published at royalityfree.com

Building A Text To Speech Converter For Beginners!

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 GitHub and a demo is available here!

Text To Speech
How Cloud Speech Works (Source: Google)

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 textToSpeech() 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 getVoices() scheme of Speech Synthesis and insert it into the attributed HTML select tag.

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

Best Text To Speech Software For Voice Over & Youtube Videos (USA 2021) - Text  To Speech Converter
Source: SugarMint

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 .html, .css and a .js 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 index.html and paste the following codes into your HTML file. Save It, you’ve to create a file with an .html 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>
Enter fullscreen mode Exit fullscreen mode

Secondly, create a CSS file with the filename of style.css and paste the following code in the file. Save It, you have to create a file with .css 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*/
Enter fullscreen mode Exit fullscreen mode

Finally, create a JavaScript file with a filename of script.js and paste the following code in your JavaScript file. Save It, you have to create a file with .js 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
        }
    }
});
Enter fullscreen mode Exit fullscreen mode

How auto Text-to-Speech works?
Source: VoximPlant

Text To Speech Converter (Last Words)

That’s it, you’ve now successfully built a Text To Speech Converter Project in native HTML, CSS, and JavaScript.

If your code does not work or you have faced any problem/issue, try downloading the source files from the provided download button below.

It’s priceless and a .zip file will be downloaded and then just extract it to your filemanager, server, etc.

Top comments (1)

Collapse
 
maadah profile image
maadah

Very nice, how can download the voice