Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Using Text to Speech with NativeScript

    Brad MartinBrad Martin

    We will use the NativeScript Text-to-Speech plugin to have the iOS and Android speech synthesizers speak a provided text.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    We'll start by adding the plugin using TNS plugin add command. The plugin is NativeScript text to speech. On our page, we're going to add a stack layout, and inside of the stack layout, we will add a button with text set to speak. Then we're going to use the TAP event to fire our function. We'll just call it "speak" also.

    In our code behind for the main page XML, here in the main page TS, we're just going to import the module, NativeScript text to speech is our plugin module. We're going to import the class TNS TextToSpeech, as well as the speak options interface from the plugin.

    Next, we need to create our function that we defined on the TAP event for the button on the UI. We called it "Speak." Now we have our function. With the plugin, we need to create an instance of the class. We'll say let TTS, which is of type TNS, text to speech, equals a new instance of the TNS text to speech. This will initialize the speech synthesizer on the native iOS and Android platforms.

    With our class initialized, we can simply call the speak method, which expects an object tied to the speak options interface that we imported from the module. We'll go ahead and create the object. The first parameter is text. This will be the text that the synthesizer will speak. We'll go ahead and just say "hello egghead."

    Another property is the speak rate, which controls the speak rate of the synthesizer. We're going to use 048. You can also control the volume. We'll just do 1.0here. You can also set the language. This is optional, of course, but we'll go en-us. There's a finished callback, which we could tie into a function. We'll just do a simple alert here that says, "Done speaking."

    When we run this and tap the button, we're going to hear the speech synthesizer speak the text "hello egghead." We set the speak rate and the volume. These are the defaults, but just to show the example, we've set them. Then once this runs, we'll see an alert pop up that says, "Done speaking."

    Now we can go ahead and tap the button, and it'll fire our speak function.

    " Hello egghead."

    There's the alert that we tied into the finished callback on the speak method.