我的textTospeech在第一次运行中正常工作,但是在应用程序使用" Back"键关闭并重新打开时,它在应用程序后不起作用。该错误是TextToSpeech: speak failed: not bound to TTS engine
和onInit
中的status
是ERROR
我有一个可以处理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");
}
}
}
我在ongreate中获得了语音加工的实例:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
voiceGenerator = VoiceGenerator.getInstance(this);
}
onstart中的tts初始化:
@Override
protected void onStart(){
super.onStart();
voiceGenerator.initializeTTS();
}
并将其关闭在ondestroy中:
@Override
protected void onDestroy() {
super.onDestroy();
voiceGenerator.shutdown();
}
关于我做错了什么的想法?
您需要在MainActivity
上实现TextToSpeech.OnInitListener
。这是一个很好的例子。
代码:
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);
}
}
}
使用onResume
@Override
protected void onResume() {
super.onResume();
myTTS = new TextToSpeech(this, this);
}
}
简单解决方案,并非所有设备都支持TextTospeach,请尝试使用不同的设备,
您只能让引擎说话,在完成OnInit之后,请在OnInit()中关注:
: if (status == TextToSpeech.SUCCESS) {
tts.speak("Hello World", TextToSpeech.QUEUE_FLUSH, null);
}