Text To Speech using JavaScript

Text To Speech using JavaScript
Code Snippet:Speech Synthesis
Author: Aleksandar Sandro Cvetković
Published: January 14, 2024
Last Updated: January 22, 2024
Downloads: 702
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to create Text-to-Speech functionality on a webpage. It comes with a basic interface with input options for text, voice, pitch, and rate. When you press the “Speak” button, the text you enter is converted to speech using the selected voice, pitch, and rate. The “Stop” button halts speech output. It’s helpful for adding a text-to-speech feature to web applications.

You can use this code to implement text-to-speech functionality on your website. It adds an interactive and engaging feature, making your site more inclusive.

How to Create Text To Speech Functionality Using JavaScript

1. In your HTML file, create a structure for the TTS interface. You can use the following HTML code as a starting point. It includes input fields for text, voice selection, pitch, and rate, along with buttons for speaking and stopping the speech.

<div class="voiceinator">
      <h1>The Voiceinator 5000</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">Hello! I love JavaScript 👍</textarea>
      <button id="stop">Stop!</button>
      <button id="speak">Speak</button>
    </div>

2. Apply the following CSS code to style the TTS interface. This will make it visually appealing and user-friendly. You can further customize the CSS to match your website’s design.

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

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

body{
  margin: 0;
  padding: 0;
  font-family: sans-serif;
  background-color: #3bc1ac;
  display: flex;
  min-height: 100vh;
  align-items: center;

  background-image: radial-gradient(
      circle at 100% 150%,
      #3bc1ac 24%,
      #42d2bb 25%,
      #42d2bb 28%,
      #3bc1ac 29%,
      #3bc1ac 36%,
      #42d2bb 36%,
      #42d2bb 40%,
      transparent 40%,
      transparent
    ),
    radial-gradient(
      circle at 0 150%,
      #3bc1ac 24%,
      #42d2bb 25%,
      #42d2bb 28%,
      #3bc1ac 29%,
      #3bc1ac 36%,
      #42d2bb 36%,
      #42d2bb 40%,
      transparent 40%,
      transparent
    ),
    radial-gradient(
      circle at 50% 100%,
      #42d2bb 10%,
      #3bc1ac 11%,
      #3bc1ac 23%,
      #42d2bb 24%,
      #42d2bb 30%,
      #3bc1ac 31%,
      #3bc1ac 43%,
      #42d2bb 44%,
      #42d2bb 50%,
      #3bc1ac 51%,
      #3bc1ac 63%,
      #42d2bb 64%,
      #42d2bb 71%,
      transparent 71%,
      transparent
    ),
    radial-gradient(
      circle at 100% 50%,
      #42d2bb 5%,
      #3bc1ac 6%,
      #3bc1ac 15%,
      #42d2bb 16%,
      #42d2bb 20%,
      #3bc1ac 21%,
      #3bc1ac 30%,
      #42d2bb 31%,
      #42d2bb 35%,
      #3bc1ac 36%,
      #3bc1ac 45%,
      #42d2bb 46%,
      #42d2bb 49%,
      transparent 50%,
      transparent
    ),
    radial-gradient(
      circle at 0 50%,
      #42d2bb 5%,
      #3bc1ac 6%,
      #3bc1ac 15%,
      #42d2bb 16%,
      #42d2bb 20%,
      #3bc1ac 21%,
      #3bc1ac 30%,
      #42d2bb 31%,
      #42d2bb 35%,
      #3bc1ac 36%,
      #3bc1ac 45%,
      #42d2bb 46%,
      #42d2bb 49%,
      transparent 50%,
      transparent
    ) !important;
  background-size: 100px 50px !important; 
}

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

.voiceinator h1 {
  width: calc(100% + 4rem);
  margin: -2rem 0 2rem -2rem;
  padding: 0.5rem;
  background: #ffc600;
  border-bottom: 5px solid #f3c010;
  text-align: center;
  font-size: 5rem;
  font-weight: 100;
  font-family: "Pacifico", cursive;
  text-shadow: 3px 3px 0 #f3c010;
}

.voiceinator input,
.voiceinator button,
.voiceinator select,
.voiceinator textarea {
  width: 100%;
  display: block;
  margin: 10px 0;
  padding: 10px;
  border: 0;
  font-size: 2rem;
  background: #f7f7f7;
  outline: 0;
}

textarea {
  height: 20rem;
}

input[type="select"] {
}

.voiceinator button {
  background: #ffc600;
  border: 0;
  width: 49%;
  float: left;
  font-family: "Pacifico", cursive;
  margin-bottom: 0;
  font-size: 2rem;
  border-bottom: 5px solid #f3c010;
  cursor: pointer;
  position: relative;
}

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

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

3. Finally, add the following JavaScript code to your project. It sets up the SpeechSynthesis API to handle text-to-speech. It also populates the voice selection dropdown with available voices. You can further customize the code to modify voice options or enhance user interactions.

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);
}

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));

That’s all! hopefully, you have successfully created Text-to-Speech feature using JavaScript. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X