我的 TextToSpeech 在第一次运行时工作正常,但在使用“后退”键关闭应用程序并重新打开后它就不起作用了。错误是 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");
}
}
}
我在 onCreate 中获取了 VoiceGenerator 的实例:
@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);
}
}
}
关于安卓 TextToSpeech : speak failed: not bound to TTS engine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41284509/