簡體   English   中英

TextToSpeech stop()無法正常工作

[英]TextToSpeech stop() not working

我試圖按返回按鈕時停止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();

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

}

在活動暫停時停止說話

也許您正在創建許多TextToSpeech對象? 則可能是您停止了錯誤的tts

嘗試簡單

if (tts == null) {
    tts = new TextToSpeech(...) {...}
}

僅初始化不存在的對象。

像這樣進行修改,這通常對我TextToSpeech :我相信您正在使用多個TextToSpeech對象,即使您認為自己不是。 這是一個普遍的問題。

@Override
    protected void onStop()
    {
        super.onStop();

        if(tts != null){
            tts.shutdown();
        }       
    }

除了評論,您還需要確保:

tts.setEngineByPackageName(enginePackageName)

包含設備上安裝的“文本到語音”引擎的有效軟件包名稱,例如com.google.android.ttscom.svox.pico

要查看有關已安裝引擎的信息,請在此處查看我的答案

不應用此參數會將在“文本到語音設置”中選擇為設備默認值的引擎綁定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM