Add Text-to-Speech Capability in Lightning Component

    Nowadays we have lot of request for customer service automation. Salesforce chat bots is one of example. Similar to that we have Text-To-Speech feature to enhance customer self‑service application with high‑quality audio.  Let us see how we can implement Text-to-Speech in lightning component.

    We have Web Speech API to enable Text-To-Speech in our application. Web Speech API enable application to handle voice data. There are two components to this API:

    1. Speech synthesis SpeechSynthesis interface, a text-to-speech component that allows programs to read out their text content.
    2. SpeechRecognition interface, which provides the ability to recognize voice context from an audio input and respond appropriately.

    This blog is focused on first component Speech Synthesis.  For reading content from any paragraph we need two API features – voice information (e.g. kind of language) and content for speak.
    Voice Information: 

    SpeechSynthesisVoice interface is used to get voice types that system supports. It has all information like current voice language, default language etc.

    Content for speak:

    SpeechSynthesisUtterance is used to get different parts of text that we want to be spoken. It also has information about how to read it (e.g. language, pitch and volume.)

    Add Text-To-Speech in Lightning Component:

    By default all Web API is accessible in Salesforce application but lightning locker service may block these service. Speech Service is also blocked by locker service. So you have to disable locker service or create lightning component in API version 39.


        <lightning:card title="Text-To-Speech">
             <lightning:textarea aura:id="speechText" name="speechText" label="Enter some text" />
             <lightning:button variant="success" label="Speak" title="Speak" onclick="{! c.handleSpeech }"/>


     handleSpeech: function(component, event, helper) {
            if('speechSynthesis' in window)
                var text=component.find("speechText").get("v.value");
           		var speech = new window.SpeechSynthesisUtterance(text);
                speech.lang = 'en-US';
                alert('speechSynthesis not supported');

    Important Attributes:

    lang: This will gets and sets the language of the utterance.

    pitch: This will gets and sets the pitch at which the utterance will be spoken at.

    text: This will gets and sets the text that will be synthesised when the utterance is spoken.

    volume: This will gets and sets the volume that the utterance will be spoken at.

    Text to Speech Demo:

    For further details check Web Speech API.

    August 1, 2019 5 comments
    1 Facebook Twitter Google + Pinterest