Bookmark
All Settings
Theme
Font Type
Font Size
The default resizer setting is 1 or 1.0.
Text to Speech
The default Speed and Pitch settings are 1 or 1.0.
Setting Default
This action can delete all settings data, themes, text-to-speech preferences, font types, bookmarks, and even browsing history.
Chat WhatsApp

Creating a Text-to-Speech Feature to Read Articles Automatically

Jejaknesia.com - Hi web developer, Welcome back with Jejaknesia. On this occasion, we will discuss in-depth how to create a Text-to-Speech feature for automatically reading articles using a combination of HTML, CSS, and JavaScript.

This feature will be very useful for improving accessibility and enhancing user experience on your website. With the ability to listen to content, visitors can enjoy your articles even when busy or having visual impairments.

Let’s dive into the steps together!

Creating a Text-to-Speech Feature to Automatically Read Articles

In the ever-evolving world of web development, user experience (UX) has become one of the main keys to a website’s success. Various innovative features continue to be developed to ensure that users can interact with content more efficiently and enjoyably. One feature that can significantly improve accessibility and ease of use is Text-to-Speech (TTS), also known as T2S.

The TTS feature allows users to listen to articles or other text content they are reading. This is not only beneficial for individuals with visual impairments but also for those who want to multitask or prefer to consume information through audio.

This article will guide you step-by-step in building a Text-to-Speech feature using basic web technologies: HTML, CSS, and JavaScript. By implementing this feature, you can provide significant added value for your website visitors, make your content more accessible, and ultimately improve SEO through enhanced user interaction.

Why Do We Need a Text-to-Speech Feature?

Before we dive into the technical details, it’s important to understand why the Text-to-Speech feature matters in web development. The feature in this article can help improve accessibility and user comfort, especially for those who may have difficulty reading text or prefer listening instead of manual reading.

By using Text-to-Speech, users can convert article text into audio they can listen to. This can be useful in various contexts, such as helping readers with visual impairments, enabling multitasking, or providing an alternative for those who prefer listening over reading.

Steps to Create the Text-to-Speech Feature

The following are the steps to create a Text-to-Speech feature to automatically read articles:

1. HTML Structure

First, we need to prepare the HTML structure for the Text-to-Speech button. Make sure the article has a clear markup, such as using <p>, <h1> to <h6> tags. Other tags will be ignored. You can also customize it in JavaScript by adding desired tags.

<!DOCTYPE html>
<!-- Created By jejaknesia.com -->
<html lang="en">
<head>
    <title>Text-to-Speech Feature | jejaknesia.com</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, pada artikel kali initial-scale=1.0">
</head>
<body>
    <button id="toggle-play">
        <svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
            <path d="M8 5v14l11-7z"/>
        </svg>
        Play
    </button>
    <div id="post-body">
        <h2>Why Do We Need a Text-to-Speech Feature?</h2>
        <p>In the world of web development, there are various ways to enhance user experience. One of them is by providing a feature that allows users to access and read articles more efficiently.</p>
        <h2>User Experience</h2>
        <p>Create a Text-to-Speech feature that can improve user experience on your website.</p>
        <p>Thank you for following the tutorial!</p>
    </div>
</body>
</html>

2. CSS Design

The style (CSS) will help you design the appearance of the Text-to-Speech feature you are building. You can adjust the layout, font, and colors as needed according to your website design. Place the following CSS code inside the <head> tag:

#post-body {
    width: 100%;
    margin: 0 auto;
}

p {
    font-size: 18px;
    line-height: 1.5;
    margin-bottom: 20px;
}

.highlighttts {
    display: inline;
}
.highlighttts:after{
    content: "";
    margin-right: -1.86px;
    border-right: 2px solid #19aee8;
    animation: kedip 1s linear infpada artikel kali inite;
}

svg.icon {
    width: 24px;
    height: 24px;
    margin-right: 8px;
    fill: #19aee8;
}
#toggle-play{
  position: relative;
  display: flex;
  align-items: center;
  border-radius: 50px;
  padding: 0 15px 0 10px;
  border: 1px solid #19aee8;
  color:#000;
  background: #fff;
}

@keyframes kedip {
    0% {
        opacity: 1;
    }
    50% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
}

3. JavaScript Implementation

This is the crucial step in creating the Text-to-Speech feature. You need to implement JavaScript to convert the article text into audio that can be played. You can use the Web Speech API or a third-party TTS library for more complex control. Place the JavaScript code below above the closing </body> tag.

// Created By jejaknesia.com
const togglePlayButton = document.getElementById("toggle-play");
const textContainer = document.getElementById("post-body");

let isPlaying = false;
let currentParagraph = 0;
const paragraphs = textContainer.querySelectorAll("p,h1,h2,h3,h4,h5,h6");
let currentHighlightedSpan = null;
let currentWordIndex = 0;

togglePlayButton.addEventListener("click", function () {
  if (!isPlaying) {
      if (currentParagraph >= paragraphs.length) {
          // Reset to start when finished
          currentParagraph = 0;
      }
      isPlaying = true;
      togglePlayButton.innerHTML = `
          <svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
              <path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/>
          </svg>
          Pause
      `;
      play();
  } else {
      isPlaying = false;
      togglePlayButton.innerHTML = `
          <svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
              <path d="M8 5v14l11-7z"/>
          </svg>
          Play
      `;
      speechSynthesis.cancel();
  }
});

function play() {
  if (currentParagraph < paragraphs.length) {
      const paragraph = paragraphs[currentParagraph];
      const text = paragraph.textContent;
      speak(text);
  } else {
      isPlaying = false;
      togglePlayButton.innerHTML = `
          <svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
              <path d="M8 5v14l11-7z"/>
          </svg>
          Play
      `;
  }
}

function speak(text) {
  const words = text.split(" ");
  const rate = 1.0; // Adjust reading speed

  function speakWord() {
      if (currentWordIndex < words.length) {
          if (currentHighlightedSpan) {
              unhighlightWord(currentHighlightedSpan);
          }
          const word = words[currentWordIndex];
          highlightWord(paragraphs[currentParagraph], currentWordIndex);
          const utterance = new SpeechSynthesisUtterance(word);
          utterance.lang = "id-ID"; // Set language
          utterance.rate = rate;
          speechSynthesis.speak(utterance);

          utterance.onend = function () {
              currentWordIndex++;
              speakWord();
          };
      } else {
          // After finishing words, move to next paragraph
          currentWordIndex = 0;
          currentParagraph++;
          setTimeout(play, 500); // Wait 500ms before next paragraph
      }
  }

  speakWord();
}

function highlightWord(paragraph, wordIndex) {
  const words = paragraph.textContent.split(" ");
  words[wordIndex] = `<span class="highlighttts">${words[wordIndex]}</span>`;
  paragraph.innerHTML = words.join(" ");
  currentHighlightedSpan = paragraph.querySelector(".highlighttts");
}

function unhighlightWord(span) {
  const text = span.textContent;
  span.outerHTML = text;
}
Make sure the article you write is placed within the post-body ID. If it’s different, adjust the ID in the JavaScript above to match the ID in your blog or website.

Some Advantages:

  1. A button that can play or pause anytime.
  2. A reading indicator marked with a highlight color.


By following the steps above, you should be able to create a Text-to-Speech feature that enhances user experience on your website. Be sure to keep up with technology developments and best practices in web development to ensure that this feature works well and provides benefits for your users.

Thank you for visiting — hope this article is helpful.