2015-02-09 743 views
1

我正在使用Android的TextToSpeech引擎。初始化代碼Android TextToSpeech初始化 - 將默認TTS引擎設置爲「android.speech.tts」

TextToSpeech mTTS; 
mTTS=new TextToSpeech(this, this, "android.speech.tts"); 
mTTS.setEngineByPackageName("android.speech.tts"); 

Intent checkTTSIntent = new Intent(); 

checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); 

startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE); 

但是這個代碼我的手機選擇器對話框選擇的B/W谷歌的文字轉語音引擎或三星的文字轉語音引擎。現在我想刪除這個

Chooser popup

選配盒,並直接加載谷歌的TTS引擎,而無需用戶交互。請幫助我被困住了:(

回答

1

With Intent(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA)我相信你正試圖檢查TTS數據是否安裝在設備上,順便說一下,這將檢查默認的設備語言,如果沒有安裝它會給resultCode爲TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA onActivityResult()

請在下面找到初始化TTS和處理錯誤的正確方法

system = SpeechRecognizer.createSpeechRecognizer(getApplicationContext()); 
system.setRecognitionListener(this); 
speech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() { 

     @Override 
     public void onInit(int status) { 
      if (status == TextToSpeech.SUCCESS) { 
        result = speech.setLanguage(Locale.US); 
        if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { 
         Log.e("TTS", "This Language is not available, attempting download"); 
         Intent installIntent = new Intent(); 
         installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA); 
         startActivity(installIntent); 
        } 
      } 
      else { 
       Log.e("TTS", "Initialization Failed!"); 
      } 
     } 
    }, "com.google.android.tts"); 

請注意3點這裏:。。

  1. 包名稱是「com.google.android.tts」,用於使用Google文本到語音。
  2. 你不需要檢查intent「ACTION_CHECK_TTS_DATA」,這將在onInit()中處理。
  3. 文本到語音setlanguage是一個昂貴的操作,它凍結了UI線程;如果你想使用默認語言,請刪除它。

使用此方法,您將不會得到對話框的任何彈出窗口,並且tts將被初始化。讓我知道它是否有幫助!