2015-02-09 125 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将被初始化。让我知道它是否有帮助!