Reputation: 7
I want my application speak a sentence "Hello, If Your Case Is Emergency CALL 911" when the activity starting, but i cannot do that.
i had used the following code:
public class home extends AppCompatActivity implements TextToSpeech.OnInitListener {
Button Signin , listButton,Speak;
EditText Text;
Button mSpeak;
private TextToSpeech mTTS;
protected static final int RESULT_SPEECH = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// TTS
mTTS = new TextToSpeech(this, this);
mSpeak = (Button) findViewById(R.id.mSpeak);
mSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
speak("Hello, If Your Case Is Emergency CALL 911 , IF not Continue");
}
});
speak("Hello, If Your Case Is Emergency CALL 911 , IF not Continue");
}
public void speak(String str) {
mTTS.speak(str, TextToSpeech.QUEUE_FLUSH, null);
}
@Override
protected void onDestroy() {
super.onDestroy();
mTTS.shutdown();
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = mTTS.setLanguage(Locale.UK);
mTTS.setPitch(0.8f);
mTTS.setSpeechRate(1.1f);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language not supported");
} else {
mSpeak.setEnabled(true);
}
} else {
Log.e("TTS", "Initialization failed");
}
}
}
in the previous code the speak(str)
method used to run TTS and let devise start speaking.
however, when i try to run TextToSpeech
when the mSpeak
Button pressed, it work correctly. but, when run it on onCreate
it not work.
I want that when the activity starts the TextToSpeech
should play. Anybody could please guide me the right way to do it as it is not working. The TextToSpeech
ONLY works with the button press.
Upvotes: 0
Views: 33
Reputation: 19273
thats because TTS is initializing for a while, pretty fast, but still you can't create new TextToSpeech
and almost immediatelly few lines below call mTTS.speak
. at this moment you don't know is TTS available - you must wait for status == TextToSpeech.SUCCESS
(and also language available confirmation), so you should move you "welcome" speak method call there
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = mTTS.setLanguage(Locale.UK);
mTTS.setPitch(0.8f);
mTTS.setSpeechRate(1.1f);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language not supported");
} else {
mSpeak.setEnabled(true);
speak("Hello, If Your Case Is Emergency CALL 911 , IF not Continue");
}
} else {
Log.e("TTS", "Initialization failed");
}
}
Upvotes: 1