Monday, October 25, 2010

A Text to Speech App

Further to our introductory example here I will show you a Text to Speech app. The app will speak out whatever you type into the edit box. Here is the source code.

(require 'android-defs)


(activity hello
  (on-create-view
    (define mTts
      (android.speech.tts.TextToSpeech
        (this)
        (lambda (i) ())))
    (android.widget.LinearLayout (this)
      orientation: android.widget.LinearLayout:VERTICAL
      view:
        (android.widget.TextView (this)
          text: "Enter the text to speak")
      view:
        (android.widget.EditText (this)
          id: 101)
      view:
        (android.widget.Button (this)
          text: "Speak!"
          on-click-listener:
            (lambda (v)
              (mTts:speak
                ((as <android.widget.EditText>
                  ((this):findViewById 101)):getText)
                android.speech.tts.TextToSpeech:QUEUE_FLUSH
                #!null))))))


Copy and paste the code above into your hello.scm file and build the app.

In the on-create-view macro we first define an instance of the android.speech.tts.TextToSpeech class and we assign it to variable mTts. The TextToSpeech class takes two arguments in its constructor.  The first argument is the context '(this)'. the second argument is an instance of the TextToSpeech.OnInitListener class. We simply pass and anonymous empty function to it and Kawa will take care of the rest.

Then we add an android.widget.EditText instance to our layout and we give it an id. In the buttons onClickListener we call the speak method of the mTts variable.

              (mTts:speak
                ((as <android.widget.EditText>
                  ((this):findViewById 101)):getText)
                android.speech.tts.TextToSpeech:QUEUE_FLUSH
                #!null))))))
Here we pass it three arguments. The first argument is the text you typed in the text box. We get hold of it with it's id and call its getText method. The second argument is the queue type and the last argument is a null.

No comments:

Post a Comment