话不多说,直接上代码
private TextToSpeech textToSpeech;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Log.d(TAG, "onInit: TTS初始化成功");
int result = textToSpeech.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.d(TAG, "onInit: 当前设置的语言不支持哦");
}
speakOut("你好呀!");
} else {
Log.d(TAG, "onInit: TTS初始化失败");
}
}
});
textToSpeech.setLanguage(Locale.CHINESE);
textToSpeech.setSpeechRate(0.6f);
textToSpeech.setPitch(1.2f);
}
public void speakOut(String text) {
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
if (textToSpeech!= null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
}