问题
So, I want to create a text to speech without the use of textfield and button in Android Studio. For example when I open the app it will say "WELCOME TO MY APP" without text field or any button. How can I do that? Need your help.
回答1:
You could do like below:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import java.util.Locale;
public class MainActivity extends Activity {
TextToSpeech t1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
t1.setLanguage(Locale.ENGLISH);
}
}
});
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
t1.speak("welcome to my app", TextToSpeech.QUEUE_FLUSH, null);
}
}, 100);
}
public void onPause() {
if (t1 != null) {
t1.stop();
t1.shutdown();
}
super.onPause();
}
}
codes are self explanatory and I tested it with successful result.
回答2:
Just add this in your onCreate():
myTTS = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
// replace this Locale with whatever you want
Locale localeToUse = new Locale("en","US");
myTTS.setLanguage(localeToUse);
myTTS.speak("Hi, Welcome to my app!", TextToSpeech.QUEUE_FLUSH, null);
}
}
});
来源:https://stackoverflow.com/questions/52133256/text-to-speech-without-textfield-and-button-in-android-studio