Android 12 更改了 TextToSpeech 的一些默认设置,导致这些方法可能不会按照预期工作。为了解决这个问题,您可以设置TextToSpeech的属性:
在onInit方法中添加以下代码:
textToSpeech.setSpeechRate(0.8f); textToSpeech.setPitch(1.2f);
这将在初始化 TextToSpeech 时设置语音速率和语音音高,以确保它们按照预期工作。完整示例如下:
private TextToSpeech textToSpeech;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
textToSpeech = new TextToSpeech(this, this);
textToSpeech.setLanguage(Locale.US);
}
@Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { int result = textToSpeech.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language not supported");
} else {
textToSpeech.setSpeechRate(0.8f);
textToSpeech.setPitch(1.2f);
textToSpeech.speak("Hello, World!", TextToSpeech.QUEUE_FLUSH, null);
}
} else {
Log.e("TTS", "Initialization failed");
}
}