1,TextToSpeech类是android自带的,但是部分设备需要支持TTS需要增加语音库,我使用的是讯飞语音(离线的哦)。请自行下载并安装讯飞语音APK,然后到系统设置中设置TTS功能默认使用该选项。有自带TTS库的可以省略该步骤。
2,定义TTS对象
private TextToSpeech mTextToSpeech=null;
3,调用,每次调用都需要初始化
try{
final String strSpeekNow = strSpeek;
mTextToSpeech=new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status==TextToSpeech.SUCCESS) {
//设置朗读语言
int supported=mTextToSpeech.setLanguage(Locale.CHINESE);
if ((supported!=TextToSpeech.LANG_AVAILABLE)&&(supported!=TextToSpeech.LANG_COUNTRY_AVAILABLE)) {
CardManager.toast(VerificationResultActivity.this, "不支持当前语言!");
}
}
//设置音调,值越大声音越尖(女生),值越小则变成男声,1.0是常规
mTextToSpeech.setPitch(1.0f);
//设置语速
mTextToSpeech.setSpeechRate(1.3f);
mTextToSpeech.speak(strSpeekNow, TextToSpeech.QUEUE_FLUSH, null, null);
}
});
} catch (Exception e) {//语音播报出错
Log.e("tts",e.toString());
}
4,在onDestroy中关闭TTS
if (mTextToSpeech!=null) {
mTextToSpeech.shutdown();//关闭TTS
}