TextToSpeech stop() 不起作用



我试图停止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();
}

除了注释之外,您需要确保:

tts.setEngineByPackageName(enginePackageName)

包含安装在设备上的文本转语音引擎的有效包名称,例如 com.google.android.ttscom.svox.pico

要检查有关已安装引擎的信息,请参阅我的答案

这里

不应用此参数将绑定在"文本到语音转换设置"中选择为设备默认值的引擎。

 public void onPause(){
  if(tts !=null){
     tts.stop();
     tts.shutdown();
  }
  super.onPause();

}

停止在活动暂停时发言

像这样修改,这通常对我有用:我相信您正在使用多个TextToSpeech对象,即使您不认为自己是。这是一个常见问题。

@Override
    protected void onStop()
    {
        super.onStop();
        if(tts != null){
            tts.shutdown();
        }       
    }

也许您正在创建许多TextToSpeech对象?那么可能是您停止了错误的tts

尝试一个简单的

if (tts == null) {
    tts = new TextToSpeech(...) {...}
}
仅初始化对象

(如果该对象尚不存在(。

最新更新