简介
TTS即从文本到语音(TextToSpeech)
一,使用第三方提供的SDK或者API,例如:科大讯飞,百度,阿里等;
二,使用Android系统自带的API :TextToSpeech
TextToSpeech中的API文档(官方):TextToSpeech | Android Developers,记录各个方法,变量,常量详细介绍;
三,TextToSpeech的使用
如下代码是做了简单封装;
public class TTSUtils extends UtteranceProgressListener {private Context mContext;private static TTSUtils singleton;private TextToSpeech textToSpeech; // 系统语音播报类private boolean isSuccess = true;public static TTSUtils getInstance(Context context) {if (singleton == null) {synchronized (TTSUtils.class) {if (singleton == null) {singleton = new TTSUtils(context);}}}return singleton;}private TTSUtils(Context context) {this.mContext = context.getApplicationContext();textToSpeech = new TextToSpeech(mContext, i -> {//系统语音初始化成功if (i == TextToSpeech.SUCCESS) {int result = textToSpeech.setLanguage(Locale.CHINA);textToSpeech.setPitch(2.0f);// 设置音调,值越大声音越尖(女生),值越小则变成男声,1.0是常规textToSpeech.setSpeechRate(1.0f);textToSpeech.setOnUtteranceProgressListener(TTSUtils.this);if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {//系统不支持中文播报isSuccess = false;}}});//百度的播放引擎 "com.baidu.duersdk.opensdk"}public void playText(String playText) {if (!isSuccess) {Toast.makeText(mContext, "系统不支持中文播报", Toast.LENGTH_SHORT).show();return;}if (textToSpeech != null) {textToSpeech.speak(playText, TextToSpeech.QUEUE_ADD, null, null);}}public void stopSpeak() {if (textToSpeech != null) {textToSpeech.stop();textToSpeech.shutdown();}}@Overridepublic void onStart(String utteranceId) {}@Overridepublic void onDone(String utteranceId) {}@Overridepublic void onError(String utteranceId) {}}
使用
在Application中进行初始化,或者在Activity中先初始化,因为TextToSpeech初始化需要时间,所以在使用之前早点初始化,不然有坑;
TTSUtils.getInstance(this);
调用
TTSUtils.getInstance(getContext()).playText("床前明月光,疑似地上霜");
问题
没有声音或者提示不支持中文
1,需要检查系统是否设置播放引擎,荣耀V30为例 设置—>辅助功能 —>无障碍 —> 文本转语音中是否安装了播放引擎;系统默认是应该是Pico TTS,不过这个不支持中文;
关于默认引擎也可以通过TextToSpeech中的
getDefaultEngine()
方法获取;
需要安装第三方播放引擎,比如:com.google.android.tts 谷歌文字转语音引擎,不支持5.0以下系统;com.iflytek.speechcloud 科大讯飞语音引擎3.0,支持4.0以上系统;com.baidu.duersdk.opensdk 度秘语音引擎3.0不支持5.0以下系统;
百度网盘下载地址密码:78td
2,根据自己需要安装引擎
3,在代码中设置引擎
在创建TextToSpeech的时候有个构造方法可以指定引擎;
public TextToSpeech(Context context, OnInitListener listener, String engine) { //engine就是要制定的引擎,这个传参其实就是引擎的包名,百度的播放引擎 "com.baidu.duersdk.opensdk" this(context, listener, engine, null, true); }
engine就是要制定的引擎,这个传参其实就是引擎的包名,百度的播放引擎 "com.baidu.duersdk.opensdk"
4,如果不在代码中设置,可以在Android设备的设置中找到“文本转语音”(一般在“无障碍”菜单下)修改自己的引擎即可,替换掉系统默认Pico TTS;