Android系統(tǒng)中大部分的手機是不支持中文TTS轉(zhuǎn)換的弦追,三星的手機一般支持捂龄,目前測試。本次安裝訊飛語音APK亭畜,協(xié)助中文TTS轉(zhuǎn)換。
1.定義一個接口毀掉用于語音的播放與暫停
public interface TTS {
void playText(String playText);
void stopSpeak();
}
2.SystemTTS類進行單例模式的編寫迎卤,同時發(fā)現(xiàn)TextToSpeech拴鸵,在實例化的同時,必須和播放的文字在一起蜗搔,不然也轉(zhuǎn)換不了劲藐。
@SuppressLint("NewApi")
public class SystemTTS extends UtteranceProgressListenerimplements TTS, TextToSpeech.OnUtteranceCompletedListener {
private ContextmContext;
private static SystemTTSsingleton;
private TextToSpeechtextToSpeech;// 系統(tǒng)語音播報類
? ? 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) {
//系統(tǒng)語音初始化成功
? ? ? ? ? ? ? ? ? ? if (i == TextToSpeech.SUCCESS) {
int result =textToSpeech.setLanguage(Locale.CHINA);
textToSpeech.setPitch(1.0f);// 設(shè)置音調(diào),值越大聲音越尖(女生)樟凄,值越小則變成男聲,1.0是常規(guī)
? ? ? ? ? ? ? ? ? ? ? ? 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();
}
}
//播報完成回調(diào)
? ? @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缝龄,然后在設(shè)置中汰现,語言和輸入挂谍,語音輸出,選擇科大訊飛服鹅,進項相關(guān)設(shè)置。
SystemTTS.getInstance(this).playText("");
進行語音的播報百新。