Android TextToSpeech 初始化 - 将默认 TTS 引擎设置为 "android.speech.tts"

Android TextToSpeech Initialization - Set default TTS engine as "android.speech.tts"

我正在研究 android 的 TextToSpeech 引擎。初始化代码是

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);

但此代码是我 phone 上的一个选择器对话框,用于选择 b/w Google 的 TextToSpeech 引擎或 Samsung TextToSpeech 引擎。现在我想删除这个

选择框并直接加载 Google 的 TTS 引擎,无需用户交互。请帮助我卡住了:(

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. 您不需要检查意图 "ACTION_CHECK_TTS_DATA",这将在 onInit().
  3. 中处理
  4. Text to Speech setlanguage 是一项开销很大的操作,它会冻结 UI 线程;如果您想使用默认语言,请将其删除。

使用此方法您将不会收到任何对话框弹出窗口,并且 tts 将被初始化。如果有帮助,请告诉我!