My TextToSpeech works fine on the first run, but it doesn't work after the application has been closed using "back" key and reopened. The error is TextToSpeech: speak failed: not bound to TTS engine
and status
in onInit
is ERROR
I have a class to handle TTS:
public class VoiceGenerator {
public TextToSpeech tts;
private Context context;
private String TAG = "Voice Generator";
private static VoiceGenerator instance;
private VoiceGenerator(Context context){
this.context = context;
}
public static VoiceGenerator getInstance(Context context){
if (instance == null) {
instance = new VoiceGenerator(context);
}
return instance;
}
public void initializeTTS() {
if (tts == null) {
Log.d(TAG, "initialize tts");
tts = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
Log.d(TAG, "initialize tts success");
tts.setLanguage(...);
}
}
});
}
}
public void speak(){
tts.speak(...)
}
public void shutdown(){
if(tts != null) {
tts.stop();
tts.shutdown();
tts=null;
Log.d(TAG, "TTS Destroyed");
}
}
}
I get the instance of VoiceGenerator in onCreate:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
voiceGenerator = VoiceGenerator.getInstance(this);
}
Initialize TTS in onStart:
@Override
protected void onStart(){
super.onStart();
voiceGenerator.initializeTTS();
}
And shut it down in onDestroy:
@Override
protected void onDestroy() {
super.onDestroy();
voiceGenerator.shutdown();
}
Any ideas on what I am doing wrong?
You need to implement TextToSpeech.OnInitListener
on the MainActivity
. Here's a good example.
Code:
public class MainActivity extends ActionBarActivity implements TextToSpeech.OnInitListener{
private TextToSpeech engine;
private EditText text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (EditText) findViewById(R.id.text);
engine = new TextToSpeech(this, this);
}
public void speakText(View v) {
String textContents = text.getText().toString();
engine.speak(textContents, TextToSpeech.QUEUE_FLUSH, null, null);
}
@Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS) {
//Setting speech Language
engine.setLanguage(Locale.ENGLISH);
engine.setPitch(1);
}
}
}
Use onResume
@Override
protected void onResume() {
super.onResume();
myTTS = new TextToSpeech(this, this);
}
}
简单的解决方案,并非所有设备都支持 TextToSpeach ,尝试使用不同的设备,
You can only let the engine speak, after onInit is done, so do following in onInit():
if (status == TextToSpeech.SUCCESS) {
tts.speak("Hello World", TextToSpeech.QUEUE_FLUSH, null);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.