layout_text_to_speech.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="在此输入文字!" android:id="@+id/textToSpeak"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_below="@id/textToSpeak" android:id="@+id/btnSpeak"/> </RelativeLayout>
AndroidTextToSpeechActivity.java
public class AndroidTextToSpeechActivity extends Activity implements TextToSpeech.OnInitListener{ EditText textToSpeak = null; Button btnSpeak = null; TextToSpeech tts; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textToSpeak = findViewById(R.id.textToSpeak); btnSpeak = findViewById(R.id.btnSpeak); btnSpeak.setEnabled(false); tts = new TextToSpeech(this, this); btnSpeak.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { speakOut(); } }); } @Override public void onDestroy() { // 不要忘记关闭tts! if (tts != null) { tts.stop(); tts.shutdown(); } super.onDestroy(); } @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { int result = tts.setLanguage(Locale.US); if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { Log.e("TTS", "This Language is not supported"); } else { btnSpeak.setEnabled(true); speakOut(); } } else { Log.e("TTS", "初始化失败!"); } } private void speakOut() { String text = textToSpeak.getText().toString(); if(text == null || text.isEmpty()) return; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { String utteranceId=this.hashCode() + ""; tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId); } else { tts.speak(text, TextToSpeech.QUEUE_FLUSH, null); } } }
被说的语言,可以通过提供一个设置Locale为setLanguage()方法:
tts.setLanguage(Locale.CHINESE); // 中文
支持的语言数量在Android级别之间有所不同。该方法isLanguageAvailable()可用于检查是否支持某种语言:
tts.isLanguageAvailable(Locale.CHINESE);
可以使用该setPitch()方法来设置语音音调级别。默认情况下,音高值为1.0。使用小于1.0的值减小音调级别,或使用大于1.0的值增大音调级别:
tts.setPitch(0.6);
可以使用设置语音速率setSpeechRate()。默认语音速率是1.0。可以通过将语音速率设置为2.0来使其翻倍,或者通过将其设置为0.5来使语音速率提高一半:
tts.setSpeechRate(2.0);