问题
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 activity class , for example i have class that genrate layout and return this layout to my main activity , ihave button on this layout and i want to when clicked on this button call text to speech. how can i use text to speech on non activity class ?
回答1:
You can use a facade to achieve this.
Define an interface for example TTSListener.java
:
public interface TTSListener{
public void speak(String text);
public void pause(long duration);
}
In your Main activity, implement the interface:
public class MainActivity extends Activity implements TTSListener{
@Override
public void speak(String text){
runOnUiThread(new Runnable() {
@Override
public void run(){
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
);
}
@Override
public void pause(long duration){
runOnUiThread(new Runnable() {
@Override
public void run(){
tts.playSilence(duration, TextToSpeech.QUEUE_FLUSH, null);
}
);
}
Then finally in your non-activity's class, you can invoke the TTS methods:
public class SomeClass{
TTSListener ttsListener;
public SomeClass(Context context){
ttsListener = (TTSListener)context;
}
ttsListener.speak("Hello");
ttsListener.pause(4000); //pause for 4 seconds
}
回答2:
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;
public class Speech {
private static TextToSpeech tts;
private static CharSequence SC_str;
private static String S_str;
public static void Talk(Context context, String str) {
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
S_str = str;
tts = new TextToSpeech(Zillion.getContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(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;
public class Zillion extends Application {
private static Context mContext;
@Override
public void onCreate() {
super.onCreate();
mContext = getApplicationContext();
}
public static Context getContext() {
return mContext;
}
}
and define the app in the manifest related to this class as:
<application
android:name=".Zillion"
</application>
来源:https://stackoverflow.com/questions/28943614/androidhow-to-use-text-to-speech-on-non-activity-class