Reputation: 1096
I want to Convert some text to Speech during oncreate method. That is when the activity starts it will speak some text. How can i do that???
I know how to work normally with tts. These are sample code. But it doesn't work when the activity starts.
public class AndroidTextToSpeechActivity extends Activity implements
TextToSpeech.OnInitListener {
/** Called when the activity is first created. */
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tts = new TextToSpeech(this, this);
btnSpeak = (Button) findViewById(R.id.btnSpeak);
txtText = (EditText) findViewById(R.id.txtText);
// button on click event
btnSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
speakOut();
}
});
}
@Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
btnSpeak.setEnabled(true);
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut() {
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
Upvotes: 2
Views: 1468
Reputation: 367
I had the same problem. I solved it by implementing the tts service a little bit different:
in onCreate:
TextToSpeech tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int i) {
methodSpeek();
}
}, "com.google.android.tts");
This way your text only starts after it is initialized.
Upvotes: 1
Reputation: 3000
Your code is playing dynamically generated speech as soon as it possibly can, because you are calling
speakOut()
in the onInit()
method, which is the callback that fires when the text-to-speech synthesizer is ready to use.
If you want to generate speech even sooner, and you know ahead of time the phrase to speak and the locale in which to speak it, you can pregenerate synthetic speech, save it into a WAV file, and play it back later with MediaPlayer
:
HashMap<String, String> myHashRender = new HashMap();
String wakeUpText = "Are you up yet?";
String destFileName = "/sdcard/myAppCache/wakeUp.wav";
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, wakeUpText);
mTts.synthesizeToFile(wakuUpText, myHashRender, destFileName);
See the article for details.
Upvotes: 0