Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    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.

    nativescriptNativeScript
    Code

    Code

    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
    Transcript

    Transcript

    00:00 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.

    00:37 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.

    01:03 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.

    01:36 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."

    02:06 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."

    02:45 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."

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

    "03:08 Hello egghead."

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

    Discuss

    Discuss