Text To Speech Using HTML and JavaScript (Source Code)
Published: 2023-05-27 04:46:12

Hello there! In this tutorial will teach you how to make a Text to Speech using HTML, CSS, and JavaScript. You have to just type your text select a voice and click on speak and it's done. and now it's time to create a **[Text To Speech](https://www.codewithrandom.com/2023/04/14/text-to-speech-using-javascript/)** Converter Web Application.

Text-to-speech (TTS) technology converts your text into spoken sounds. You can convert your text to speech in different voices with this project (Text To Speech Converter App). If your text character length exceeds 80, you can also pause and resume using stop and speak button.

It was created with HTML, CSS, and plain JavaScript. This TTS program uses no external JavaScript libraries or APIs, and I hope you will enjoy our article.

I shared How to Build a Currency Converter App in HTML, CSS, and JavaScript in an earlier blog; if you haven't read that yet, just click the link below,

**Prerequisites:**
```
index.html - For adding structure to the project
styles.css: For adding styling to the project
script.js - For adding drag and drop or browse features.
```
I hope now you have a general idea of what the project entails. In our article, we will go over this project step by step.

## Step1: Text to Speech Html Code:-

Create an HTML file called index.html and paste the following codes into it. Remember to save the file with the .html extension.
```
<html lang="en">

<head>
    <link rel="stylesheet" href="style.css">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>

<body>
    <!-- Works best in Chrome! -->
<div class="voiceinator">
    <h1>Text-To-Speech Converter</h1>
    <select name="voice" id="voices">
      <option value="">Select A Voice</option>
    </select>
    <label for="rate">Rate:</label>
    <input name="rate" type="range" min="0" max="3" value="1" step="0.1">
    <label for="pitch">Pitch:</label>
    <input name="pitch" type="range" min="0" max="2" step="0.1">
    <textarea name="text" placeholder="Start typing...">Follow CodewithRandom </textarea>
    <button id="stop">Stop</button>
    <button id="speak">Speak</button>
  </div>
    <script src="script.js"></script>
</body>

</html>
```
We'll begin by adding the project's structure, but first we'll need to include certain items inside the link, such as the fact that we've used multiple CSS and javascript files, which we'll need to link up inside our HTML file.
```
//Head Section
<link rel="stylesheet" href="style.css">
//Body Section
<script src="script.js"></script>
```
Now we'll put the structure of our text-to-speech converter within the body tag. The div tag will be used to build a container for our text-to-speech converter. Using the h1 tag, we will add a header for our text-to-speech converter inside our div. We'll add numerous voices to our text-to-speech converter and generate a list of alternatives for different voices using the <select> element.

Now we'll add two sliders by using the <input> tag with the type set to range. The first slider will be used to change the voice rate. We can change the speed of the voices by dragging the slider. The second slider will be used to adjust the pitch of the voice between high and low.

Now, we'll utilise the <textarea> element to build a text area where the user may write text and the voice-over artist will read it. Now, we'll make two buttons with the button tag: stop and speak.

We don't need anything else to develop the structure for our Text-to-speech converter. We'll style our TTS now that we've learned how to use CSS. But first, let's have a peek at our framework.

## Step2: Adding CSS Code:-

Cascading Style Sheets (CSS) is a markup language for describing the presentation of a document written in HTML or XML. CSS, like HTML and JavaScript, is a key component of the World Wide Web. Create a CSS file with the name style.css and paste the following codes into it. Always save the file with the.css extension.
```
@import url("https://fonts.googleapis.com/css?family=PT+Sans");

html {
  font-size: 10px;
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  margin: 0;
  padding: 0;
  font-family: "PT Sans", sans-serif;
  background-color: #d5d9e5;
  color: #292b2c;
  display: flex;
  min-height: 100vh;
  align-items: center;
}

.voiceinator {
  padding: 2rem;
  width: 50rem;
  margin: 0 auto;
  border-radius: 1rem;
  position: relative;
  background: #fff;
  overflow: hidden;
  z-index: 1;
  box-shadow: 0 0 5px 5px rgba(0, 0, 0, 0.1);
}

h1 {
  width: calc(100% + 4rem);
  margin: 0 0 2rem -2rem;
  padding: 0.5rem;
  text-align: center;
  font-size: 4rem;
  font-weight: 100;
  font-family: "PT Sans", sans-serif;
}

.voiceinator input,
.voiceinator button,
.voiceinator select,
.voiceinator textarea {
  width: 100%;
  display: block;
  margin: 10px 0;
  padding: 10px;
  font-size: 2rem;
  background: #fbfbfc;
  outline: 0;
  font-family: "PT Sans", sans-serif;
  border: 1px solid #c8c7cb;
  border-radius: 2px;
}

label {
  font-size: 2rem;
}

textarea {
  height: 20rem;
}

.voiceinator button {
  background: #72a3da;
  color: #fff;
  border: 0;
  width: 49%;
  float: left;
  font-family: "PT Sans", sans-serif;
  margin-bottom: 0;
  font-size: 2rem;
  cursor: pointer;
  position: relative;
}

.voiceinator button:active {
  top: 2px;
}

.voiceinator button:nth-of-type(1) {
  margin-right: 2%;
}

input[type="range"] {
  -webkit-appearance: none;
  border: 1px solid transparent;
  padding-top: 8px;
  background: #fff;
}

input[type="range"]::-webkit-slider-runnable-track {
  height: 5px;
  background: #e1e1e3;
  border: none;
}

input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  border: none;
  height: 14px;
  width: 14px;
  border-radius: 50%;
  background: #72a3da;
  margin-top: -4px;
}

input[type="range"]:focus {
  outline: none;
}

input[type="range"]:focus::-webkit-slider-runnable-track {
  background: #ccc;
}

input[type="range"]::-moz-range-track {
  height: 5px;
  background: #e1e1e3;
  border: none;
}

input[type="range"]::-moz-range-thumb {
  border: none;
  height: 14px;
  width: 14px;
  border-radius: 50%;
  background: #72a3da;
}

input[type="range"]:-moz-focusring {
  outline: 1px solid #dcdde2;
  outline-offset: -1px;
}

.voiceinator select {
  display: inline-block;
  appearance: none;
  -moz-appearance: none;
  -webkit-appearance: none;
  outline: none;
  background: #fbfbfc
    url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="%23c8c7cb" viewBox="0 0 20 20"><path d="M5 8l6 6 6-6z"/></svg>')
    right 5px center no-repeat;
  padding: 10px 40px 10px 10px;
}

select::-ms-expand {
  display: none;
}
```
**Step1:** will first use the Google import link to import the link for the Google fonts. We will now add styling to our body using the HTML tag selector. We will adjust the font-size of our body using the font-size property, and we will set the box-sizing to "border-box" using the box-sizing property. We will also the margin and padding as "zero".

Using the background property we will change background as light blue and display is set to flex . Using the align-item property we will aling the items to the "center".
```
@import url("https://fonts.googleapis.com/css?family=PT+Sans");

html {
  font-size: 10px;
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

body {
  margin: 0;
  padding: 0;
  font-family: "PT Sans", sans-serif;
  background-color: #d5d9e5;
  color: #292b2c;
  display: flex;
  min-height: 100vh;
  align-items: center;
}
```
**Step2:** We will now add styling to our container using the class selector (.voicenator). To give some smooth edges, we will add a padding of 20px, set the width to 5o, and use the border radius property to add a border radius of 1rem. We will add a box shadow to our TTS converter by using the box-shadow property.
```
.voiceinator {
  padding: 2rem;
  width: 50rem;
  margin: 0 auto;
  border-radius: 1rem;
  position: relative;
  background: #fff;
  overflow: hidden;
  z-index: 1;
  box-shadow: 0 0 5px 5px rgba(0, 0, 0, 0.1);
}
```
**Step3:** Now we'll use the tag selector (h1) to add styling to our HTML element, calculate the width, and add an extra 4 rem with 100% width to our heading. We will also use the text-align property to center the text, and the font-family property to set the font family as "PT-Sans."

Using the multiple class selector, we will add a common style to our input, button, select, and textarea. We will set their width to 100% and the display property to "block." We'll also insert some padding and margin. We'll make the backdrop white with a border of 2 pixels of solid grey.
```
h1 {
  width: calc(100% + 4rem);
  margin: 0 0 2rem -2rem;
  padding: 0.5rem;
  text-align: center;
  font-size: 4rem;
  font-weight: 100;
  font-family: "PT Sans", sans-serif;
}

.voiceinator input,
.voiceinator button,
.voiceinator select,
.voiceinator textarea {
  width: 100%;
  display: block;
  margin: 10px 0;
  padding: 10px;
  font-size: 2rem;
  background: #fbfbfc;
  outline: 0;
  font-family: "PT Sans", sans-serif;
  border: 1px solid #c8c7cb;
  border-radius: 2px;
}
```
**Step4:** Now all we need to do is style our labels and buttons. Our label will have a font size of 2 rem and a textarea height of 20 px.

We will now add some height and background colour to our input type of using the input type selector "range Using the class selector will make our option appear as "inline-block and an SVG for the background.
```
label {
  font-size: 2rem;
}

textarea {
  height: 20rem;
}

.voiceinator button {
  background: #72a3da;
  color: #fff;
  border: 0;
  width: 49%;
  float: left;
  font-family: "PT Sans", sans-serif;
  margin-bottom: 0;
  font-size: 2rem;
  cursor: pointer;
  position: relative;
}

.voiceinator button:active {
  top: 2px;
}

.voiceinator button:nth-of-type(1) {
  margin-right: 2%;
}

input[type="range"] {
  -webkit-appearance: none;
  border: 1px solid transparent;
  padding-top: 8px;
  background: #fff;
}

input[type="range"]::-webkit-slider-runnable-track {
  height: 5px;
  background: #e1e1e3;
  border: none;
}

input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  border: none;
  height: 14px;
  width: 14px;
  border-radius: 50%;
  background: #72a3da;
  margin-top: -4px;
}

input[type="range"]:focus {
  outline: none;
}

input[type="range"]:focus::-webkit-slider-runnable-track {
  background: #ccc;
}

input[type="range"]::-moz-range-track {
  height: 5px;
  background: #e1e1e3;
  border: none;
}

input[type="range"]::-moz-range-thumb {
  border: none;
  height: 14px;
  width: 14px;
  border-radius: 50%;
  background: #72a3da;
}

input[type="range"]:-moz-focusring {
  outline: 1px solid #dcdde2;
  outline-offset: -1px;
}

.voiceinator select {
  display: inline-block;
  appearance: none;
  -moz-appearance: none;
  -webkit-appearance: none;
  outline: none;
  background: #fbfbfc
    url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="%23c8c7cb" viewBox="0 0 20 20"><path d="M5 8l6 6 6-6z"/></svg>')
    right 5px center no-repeat;
  padding: 10px 40px 10px 10px;
}

select::-ms-expand {
  display: none;
}
```
## Step3: Text to Speech Html Code:-

Finally, create a JavaScript file called script.js and paste the following codes into it. Remember to save the file with the.js extension.
```
const msg = new SpeechSynthesisUtterance();
let voices = [];
const voicesDropdown = document.querySelector('[name="voice"]');
const options = document.querySelectorAll('[type="range"], [name="text"]');
const speakButton = document.querySelector("#speak");
const stopButton = document.querySelector("#stop");
msg.text = document.querySelector('[name="text"]').value;

function populateVoices() {
  voices = this.getVoices();
  voicesDropdown.innerHTML = voices
    .filter((voice) => voice.lang.includes("en"))
    .map(
      (voice) =>
        `<option value="${voice.name}">${voice.name} (${voice.lang})</option>`
    )
    .join("");
}

function setVoice() {
  msg.voice = voices.find((voice) => voice.name === this.value);
  toggle();
}

function toggle(startOver = true) {
  speechSynthesis.cancel();

  if (startOver) {
    speechSynthesis.speak(msg);
  }
}

function setOption() {
  console.log(this.name, this.value);
  msg[this.name] = this.value;
  toggle();
}

speechSynthesis.addEventListener("voiceschanged", populateVoices);
voicesDropdown.addEventListener("change", setVoice);
options.forEach((option) => option.addEventListener("change", setOption));
speakButton.addEventListener("click", toggle);
stopButton.addEventListener("click", () => toggle(false));
```
To begin, we will use the new keyword to make an instance of the variable message, and the let keyword to establish an empty array of voices.

We will select all HTML elements and store their values in a constant variable using the document.queryselector() method.
Now we will save the value of our message variable and use the document to choose the content of our textarea. queryselector with an HTML name.

Now we will create a function populatevoices() inside the function using the this.getVoices() method returns a list of SpeechSynthesisVoice objects representing all available voices on the current device.

Now we will set the voice for that we will create a setvoice() function we will set the voice.

we will create a toggle function with a parameter startover = true , if the speech.synthesis then voice will speakout the message in the text area.

Now we will add eventlistener to the voicechange ,stop and speak button.

Now we've completed our Text to speech using HTML, CSS & javascript. I hope you understood the whole project.

Now We have Successfully created our **[Text to speech](https://www.codewithrandom.com/2023/04/14/text-to-speech-using-javascript/)** using HTML, CSS & javascript. You can use this project directly by copying it into your  IDE. We hope you understood the project, If you have any doubts feel free to comment!!

If you find out this Blog helpful, then make sure to search Codewithrandom on Google for Front End Projects with Source codes and make sure to Follow the Code with Random Instagram page.

follow : codewithrandom

Written By : Arun

Code By: Katherine kato