Social Proof

Text to Speech API with JavaScript: A Beginner's Tutorial

We're thrilled to unveil the development of a text-to-speech API that delivers Speechify's most natural and beloved AI voices directly to developers worldwide.
Join Waitlist

Looking for our Text to Speech Reader?

Featured In

Wall Street JournalForbesOCBSTimeThe New York Times
Listen to this article with Speechify!
Speechify

Hey there! If you're curious about integrating text-to-speech (TTS) capabilities into your web applications, you've come to the right place. I'll walk you through the process of using JavaScript to convert text into speech using the Web Speech API. By the end of this tutorial, you'll have a basic understanding of how to implement a text-to-speech feature, and we'll cover a lot of ground including compatibility across different browsers like Chrome, Firefox, Edge, and even mobile platforms like iOS and Android.

Getting Started

First things first, let's set up a basic HTML structure. Here's a simple "Hello World" example to get us started:


CSS
body {

            font-family: Arial, sans-serif;

            text-align: center;

            margin-top: 50px;

        }

        #text-input {

            width: 80%;

            padding: 10px;

            font-size: 16px;

        }

        #speak-btn {

            padding: 10px 20px;

            font-size: 16px;

            margin-top: 10px;

        }

html
    <div>

        <h1>Text to Speech Demo</h1>

        <textarea id="text-input" rows="5" placeholder="Enter text here..."></textarea><br>

        <button id="speak-btn">Speak</button>

    </div>

    <script src="script.js"></script>

This sets up a basic HTML page with a text input area and a button to trigger the speech.

JavaScript Implementation

Now, let's dive into the JavaScript part. We'll create a new file called script.js to handle our TTS functionality.

Initializing the Speech Synthesis

First, we need to check if the window.speechSynthesis API is available in the browser. This API provides the main interface for controlling the speech synthesis.


javascript

if ('speechSynthesis' in window) {

    console.log('Speech Synthesis API is supported.');

} else {

    console.log('Speech Synthesis API is not supported.');

}

Converting Text to Speech

Next, let's write the code to convert text to speech when the button is clicked. We'll use the SpeechSynthesisUtterance object to create a new speech utterance and the speechSynthesis.speak method to actually speak the text.


javascript

document.addEventListener('DOMContentLoaded', function() {

    const speakButton = document.getElementById('speak-btn');

    const textInput = document.getElementById('text-input');

    speakButton.addEventListener('click', function() {

        const text = textInput.value;

        const utterance = new SpeechSynthesisUtterance(text);

        speechSynthesis.speak(utterance);

    });

});

Handling Available Voices

Different browsers and platforms support different voices. We can list the available voices using the speechSynthesis.getVoices method and allow the user to select a voice.


javascript

document.addEventListener('DOMContentLoaded', function() {

    const speakButton = document.getElementById('speak-btn');

    const textInput = document.getElementById('text-input');

    const voiceSelect = document.createElement('select');

    document.body.insertBefore(voiceSelect, speakButton);

    function populateVoiceList() {

        const voices = speechSynthesis.getVoices();

        voiceSelect.innerHTML = '';

        voices.forEach((voice, index) => {

            const option = document.createElement('option');

            option.textContent = ${voice.name} (${voice.lang});

            option.value = index;

            voiceSelect.appendChild(option);

        });

    }

    populateVoiceList();

    speechSynthesis.onvoiceschanged = populateVoiceList;

    speakButton.addEventListener('click', function() {

        const text = textInput.value;

        const utterance = new SpeechSynthesisUtterance(text);

        const selectedVoice = speechSynthesis.getVoices()[voiceSelect.value];

        utterance.voice = selectedVoice;

        speechSynthesis.speak(utterance);

    });

});

Compatibility and Testing

The Web Speech API is supported in modern browsers like Chrome, Firefox, Edge, and Safari. However, the availability of voices and certain features may vary. For the best results, make sure to test your application across different browsers and devices.

Additional Features

You can further enhance your TTS functionality by adding more controls such as rate, pitch, and volume. Here’s an example of how you can include these controls:


html

<div>

    <label for="rate">Rate:</label>

    <input type="range" id="rate" min="0.1" max="2" value="1" step="0.1">

</div>

<div>

    <label for="pitch">Pitch:</label>

    <input type="range" id="pitch" min="0" max="2" value="1" step="0.1">

</div>

javascript

const rateInput = document.getElementById('rate');

const pitchInput = document.getElementById('pitch');

speakButton.addEventListener('click', function() {

    const text = textInput.value;

    const utterance = new SpeechSynthesisUtterance(text);

    const selectedVoice = speechSynthesis.getVoices()[voiceSelect.value];

    utterance.voice = selectedVoice;

    utterance.rate = rateInput.value;

    utterance.pitch = pitchInput.value;

    speechSynthesis.speak(utterance);

});

Integrating text-to-speech functionality in your web applications can greatly enhance accessibility and user experience. With just a few lines of code, you can provide a way for users to hear content instead of reading it. The Web Speech API makes it straightforward to implement TTS features in JavaScript, and with a bit of CSS styling, you can create an engaging and interactive user interface.

Feel free to explore more advanced features and customize the code to suit your needs. You can find the complete code for this tutorial on my GitHub repository.

Speechify Text to Speech API

The Speechify Text to Speech API is a powerful tool designed to convert written text into spoken words, enhancing accessibility and user experience across various applications. It leverages advanced speech synthesis technology to deliver natural-sounding voices in multiple languages, making it an ideal solution for developers looking to implement audio reading features in apps, websites, and e-learning platforms.

With its easy-to-use API, Speechify enables seamless integration and customization, allowing for a wide range of applications from reading aids for the visually impaired to interactive voice response systems.

To do text to speech in JavaScript, use the Web Speech API by creating a SpeechSynthesisUtterance object and calling speechSynthesis.speak() with the text you want to convert to speech.

To use Google Speech-to-Text API in JavaScript, you need to initialize the API client with your credentials, then use the API's speech recognition features to convert audio to text, often involving server-side code with Node.js or Python.

The Web Speech API for text-to-speech is free and built into most modern browsers, while other third-party TTS services may have usage limits or fees.

To create a text-to-speech API, you can leverage the Web Speech API for frontend implementations or use a backend service like Node.js to handle requests, synthesize speech, and manage the list of voices and language options, including English.

Cliff Weitzman

Cliff Weitzman

Cliff Weitzman is a dyslexia advocate and the CEO and founder of Speechify, the #1 text-to-speech app in the world, totaling over 100,000 5-star reviews and ranking first place in the App Store for the News & Magazines category. In 2017, Weitzman was named to the Forbes 30 under 30 list for his work making the internet more accessible to people with learning disabilities. Cliff Weitzman has been featured in EdSurge, Inc., PC Mag, Entrepreneur, Mashable, among other leading outlets.