当按下后退按钮时,我正在尝试停止TextToSpeech。但是,即使我关闭了我的应用程序,语音也不会停止。只有当我清除缓存时,语音才会停止。我怎么才能解决这个问题呢?请帮我理解一下。
private boolean mShouldSpeak = true;
TextToSpeech tts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cat);
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
tts.setEngineByPackageName(enginePackageName);
tts.setLanguage(Locale.getDefault());
tts.setPitch(0);
tts.setSpeechRate(1);
speak();
}
}
});
}
private void speak() {
if (mShouldSpeak == true)
{
tts.speak("Автор: " +getResources().getString(R.string.catAuthor), TextToSpeech.QUEUE_ADD, null);
tts.playSilence(1000, TextToSpeech.QUEUE_ADD, null);
tts.speak(getResources().getString(R.string.catName), TextToSpeech.QUEUE_ADD, null);
tts.playSilence(1000, TextToSpeech.QUEUE_ADD, null);
tts.speak(getResources().getString(R.string.catDesc), TextToSpeech.QUEUE_ADD, null);
tts.playSilence(1000, TextToSpeech.QUEUE_ADD, null);
}
}
@Override
protected void onDestroy() {
if (tts != null)
{
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void onBackPressed() {
onDestroy();
super.onBackPressed();
}发布于 2018-01-23 00:47:07
对于这些评论,您需要确保:
tts.setEngineByPackageName(enginePackageName)
包含安装在设备上的文本到语音转换引擎的有效包名称,如com.google.android.tts或com.svox.pico。
要查看有关已安装引擎的信息,请参阅my answer here
不应用此参数将绑定在文本到语音设置中选择为设备默认值的引擎。
发布于 2018-01-22 17:02:48
public void onPause(){
if(tts !=null){
tts.stop();
tts.shutdown();
}
super.onPause();}
在活动暂停时停止发言
发布于 2018-01-22 17:16:14
也许你正在创建大量的TextToSpeech对象?那么可能是您停止了错误的tts。
尝试一个简单的
if (tts == null) {
tts = new TextToSpeech(...) {...}
}仅在对象不存在时才对其进行初始化。
https://stackoverflow.com/questions/48377561
复制相似问题