Android系统中大部分的手机是不支持中文TTS转换的,三星的手机一般支持,目前测试。本次安装讯飞语音APK,协助中文TTS转换。
1.定义一个接口毁掉用于语音的播放与暂停
public interface TTS {
void playText(String playText);
void stopSpeak();
}
2.SystemTTS类进行单例模式的编写,同时发现TextToSpeech,在实例化的同时,必须和播放的文字在一起,不然也转换不了。
@SuppressLint("NewApi")
public class SystemTTS extends UtteranceProgressListenerimplements TTS, TextToSpeech.OnUtteranceCompletedListener {
private ContextmContext;
private static SystemTTSsingleton;
private TextToSpeechtextToSpeech;// 系统语音播报类
public static SystemTTS getInstance(Context context) {
if (singleton ==null) {
synchronized (SystemTTS.class) {
if (singleton ==null) {
singleton =new SystemTTS(context);
}
}
}
return singleton;
}
public SystemTTS(final Context context) {
this.mContext = context.getApplicationContext();
}
public void playText(final String playText) {
if (textToSpeech ==null) {
textToSpeech =new TextToSpeech(mContext,new TextToSpeech.OnInitListener() {
@Override
public void onInit(int i) {
//系统语音初始化成功
if (i == TextToSpeech.SUCCESS) {
int result =textToSpeech.setLanguage(Locale.CHINA);
textToSpeech.setPitch(1.0f);// 设置音调,值越大声音越尖(女生),值越小则变成男声,1.0是常规
textToSpeech.setSpeechRate(1.0f);
textToSpeech.setOnUtteranceProgressListener(SystemTTS.this);
textToSpeech.setOnUtteranceCompletedListener(SystemTTS.this);
//播放文字的时,必须和初始化在一起
textToSpeech.speak(playText, TextToSpeech.QUEUE_ADD,null,null);
if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE
&& result != TextToSpeech.LANG_AVAILABLE) {
Log.e("ddddd","TTS暂时不支持这种语音的朗读!");
}
}
}
});
}else {
textToSpeech.speak(playText, TextToSpeech.QUEUE_ADD,null,null);
}
}
public void stopSpeak() {
if (textToSpeech !=null) {
textToSpeech.stop();
}
}
public void shutDown() {
if (textToSpeech !=null) {
textToSpeech.shutdown();
}
}
//播报完成回调
@Override
public void onUtteranceCompleted(String utteranceId) {
}
@Override
public void onStart(String utteranceId) {
}
@Override
public void onDone(String utteranceId) {
}
@Override
public void onError(String utteranceId) {
}
}
安装一个讯飞讯飞APK,然后在设置中,语言和输入,语音输出,选择科大讯飞,进项相关设置。
SystemTTS.getInstance(this).playText("");
进行语音的播报。