Skip to content Skip to sidebar Skip to footer

Android:how To Use Text To Speech On Non Activity Class

i want to use text to speech in my application, i find many example for using text to speech like this Android Text-To-Speech Application . i want to use text to speech from non ac

Solution 1:

Create your Speech class as below:

package zillion;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.widget.Toast;

import java.util.Locale;


publicclassSpeech {
    privatestatic TextToSpeech tts;
    privatestatic CharSequence SC_str;
    privatestatic String S_str;

    publicstaticvoidTalk(Context context, String str) {
        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        S_str = str;
        tts = newTextToSpeech(Zillion.getContext(), newTextToSpeech.OnInitListener() {

            @OverridepublicvoidonInit(int status) {
                if(status != TextToSpeech.ERROR) {
                    tts.setLanguage(Locale.UK);
                    tts.setPitch(1.3f);
                    tts.setSpeechRate(1f);
                 //   tts.speak(SC_str, TextToSpeech.QUEUE_FLUSH, null,null);
                    tts.speak(S_str, TextToSpeech.QUEUE_FLUSH, null);
                }
            }
        });
    }
}

As you noticed Zillion.getContext() had been used as replacement of getApplicationContext(), to get the context, you need to create a class extends application, like below:

package zillion;

import android.app.Application;
import android.content.Context;

publicclassZillionextendsApplication {

    privatestatic Context mContext;

    @OverridepublicvoidonCreate() {
        super.onCreate();
        mContext = getApplicationContext();
    }

    publicstatic Context getContext() {
        return mContext;
    }
}

and define the app in the manifest related to this class as:

<application
        android:name=".Zillion"
</application>

Solution 2:

You can use a facade to achieve this.

Define an interface for example TTSListener.java:

publicinterfaceTTSListener{
publicvoidspeak(String text);
publicvoidpause(long duration);
}

In your Main activity, implement the interface:

publicclassMainActivityextendsActivityimplementsTTSListener{

@Overridepublicvoidspeak(String text){
runOnUiThread(newRunnable() {
   @Overridepublicvoidrun(){
      tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
   }
  );
 }

@Overridepublicvoidpause(long duration){
runOnUiThread(newRunnable() {
   @Overridepublicvoidrun(){
        tts.playSilence(duration, TextToSpeech.QUEUE_FLUSH, null);
   }
  );

}

Then finally in your non-activity's class, you can invoke the TTS methods:

publicclassSomeClass{
    TTSListener ttsListener;


    publicSomeClass(Context context){  
    ttsListener = (TTSListener)context;
    }

   ttsListener.speak("Hello"); 
   ttsListener.pause(4000);   //pause for 4 seconds

}

Post a Comment for "Android:how To Use Text To Speech On Non Activity Class"