只要手機帶有語音助手的話一般就會存在中文語音引擎,如果沒有的話需要額外下載中文的語音引擎,不然不支持中文。
開工,第一步,初始化:
private TextToSpeech tts;
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.CHINA);
if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE && result != TextToSpeech.LANG_AVAILABLE) {
Toast.makeText(MainActivity.this, "TTS不支持中文", Toast.LENGTH_SHORT).show();
}
}
}
});
第二步,控制:
//設置語速
tts.setSpeechRate(1.0f);
//設置語調
tts.setPitch(1.5f);
//開始朗讀
tts.speak("朗讀的文字內容", TextToSpeech.QUEUE_FLUSH, null,getString(R.string.app_name));
回調監聽:
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
//utteranceId是speak方法中最後一個參數:唯一標識碼
}
@Override
public void onDone(String utteranceId) {
}
@Override
public void onError(String utteranceId) {
//這個onError方法已過時,用下面這個方法代替
}
@Override
public void onError(String utteranceId,int errorCode) {
//這個方法代替上面那個過時方法
}
});
OK,代碼部分完成,收工。接下來是參數解釋:
setSpeechRate(float speechRate)
- speechRate:速率:默認是1.0f,可選0.5f~2.0f
setPitch(float pitch)
- pitch:音調:默認是1.0。貌似這個參數的設置不怎麼起作用。
speak(final CharSequence text, final int queueMode,final Bundle params,final String utteranceId)
- text:朗讀的內容(長度4000以內)
- queueMode:隊列模式:
- 可選參數:
- TextToSpeech.QUEUE_FLUSH:打斷已有朗讀,立即朗讀這段。
- TextToSpeech.UEUE_ADD:讀完正在讀的再讀這段。
- params:請求的參數。可爲空。
- 可選參數名稱:
- TextToSpeech.KEY_PARAM_STREAM
- TextToSpeech.KEY_PARAM_VOLUME
- TextToSpeech.KEY_PARAM_PAN
- utteranceId:這個請求唯一的標識。
setLanguage(final Locale loc)
- loc:語種
- 可選參數:(以下是源碼,可選參數爲以下的字段名)
/** Useful constant for country. */ static public final Locale FRANCE = createConstant("fr", "FR"); /** Useful constant for country. */ static public final Locale GERMANY = createConstant("de", "DE"); /** Useful constant for country. */ static public final Locale ITALY = createConstant("it", "IT"); /** Useful constant for country. */ static public final Locale JAPAN = createConstant("ja", "JP"); /** Useful constant for country. */ static public final Locale KOREA = createConstant("ko", "KR"); /** Useful constant for country. */ static public final Locale CHINA = SIMPLIFIED_CHINESE; /** Useful constant for country. */ static public final Locale PRC = SIMPLIFIED_CHINESE; /** Useful constant for country. */ static public final Locale TAIWAN = TRADITIONAL_CHINESE; /** Useful constant for country. */ static public final Locale UK = createConstant("en", "GB"); /** Useful constant for country. */ static public final Locale US = createConstant("en", "US"); /** Useful constant for country. */ static public final Locale CANADA = createConstant("en", "CA"); /** Useful constant for country. */ static public final Locale CANADA_FRENCH = createConstant("fr", "CA");
如何切換髮音人:
設置 —— 輔助功能 —— 無障礙 ——TTS文本轉語音 —— 切換引擎(如果有多個引擎的話)
引擎右邊設置可點擊進入選擇發音人(如果有的話)
科大訊飛語音引擎3.0支持多個人物的語音切換,可以自行下載這個引擎。
完。