DEV Community

Cover image for 🦜 JS Text To Voice
alexpaper
alexpaper

Posted on

4 4

🦜 JS Text To Voice

As you know Web Speech API enables you to incorporate voice data into web apps. The Web Speech API has two parts:
SpeechSynthesis (Text-to-Speech), and
SpeechRecognition (Asynchronous Speech Recognition).

Using Speech Synthesis Utterance you can create a super simple Html Css and Javascript 'Text To Voice' Web App,

For the HTML part, you just need an input field and a button, like this

<div class="container">
        <div class="box">
            <h1>🦜 Text To Voice</h1>
            <input class="text" type="text" placeholder="Text To Voice">
            <button class="play">Play</button>
        </div>
    </div>
Enter fullscreen mode Exit fullscreen mode

For the javascrit part you just need to instantiate a new SpeechSynthesisUtterance interface of the Web Speech API that represents a speech request, then you need to add the content the speech service should read and information about how to read it (e.g. language, pitch, text and volume, like this

let utter = new SpeechSynthesisUtterance();
utter.text = 'Hello World';
utter.volume = 0.5; // From 0 to 1
// utter.lang = 'us-EN';
utter.voice = voices[33]; // 33 english voice, 53 it
Enter fullscreen mode Exit fullscreen mode

Now to transform the text into voice 🎀, you can use speechSynthesis speak method, like this;

window.speechSynthesis.speak(utter);
Enter fullscreen mode Exit fullscreen mode

Finally, through the use of events, you can create a nice user experience!

 // START EVENT LISTENER
       utter.addEventListener('start',()=>{
        if(window.speechSynthesis.speaking){
            play.classList.add('active');
        }
        });
Enter fullscreen mode Exit fullscreen mode

This is a super fast video guide.
πŸ‘‹

Image of Bright Data

Feed Your Models Real-Time Data – Enhance your AI with up-to-the-minute data.

Utilize our live data feeds for dynamic model training, ensuring your AI systems are always ahead.

Access Real-Time Data

Top comments (0)

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay