原文地址:Android 語音播放(文字TTS) | Stars-One的雜貨小窩
基於Google內置的TTS引擎,封裝了個語音播放的工具類
使用
//初始化
SpeechService.init(this);
//在如何地方調用都可以
SpeechService.speakText("這是一段文本的語音測試");
//別忘記釋放資源
SpeechService.release();
坑說明
1.Flyme系統不支持
測試發現,如果是魅族手機,Flyme系統已經把TTS引擎刪了,所以會出現語音引擎初始化失敗的原因,可以試着安裝下其他的TTS引擎來進行嘗試
2.Android 11無法播放
需要在清單文件假如下面代碼
<queries>
<intent>
<action android:name="android.intent.action.TTS_SERVICE" />
</intent>
</queries>
如下圖所示
工具類源碼
public class SpeechService {
private static TextToSpeech textToSpeech;
/**
* 初始化
* @param activity
* @return
*/
public static void init(Activity activity) {
if (textToSpeech == null) {
//初始化tts語音
textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
// 如果裝載TTS引擎成功
if (status == TextToSpeech.SUCCESS) {
// 設置使用美式英語朗讀
int result = textToSpeech.setLanguage(Locale.CHINA);
// 如果不支持所設置的語言
if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE
&& result != TextToSpeech.LANG_AVAILABLE) {
ToastUtils.showShort("該tts不支持中文");
}
} else {
textToSpeech = null;
}
}
});
}
}
/**
* 朗讀語音
* @param text
*/
public static void speakText(String text) {
if (textToSpeech != null) {
textToSpeech.speak(text, TextToSpeech.QUEUE_ADD, null);
} else {
Log.e("test","語音還未初始化");
}
}
/**
* 關閉並釋放資源
*/
public static void release() {
if (textToSpeech != null) {
// 不管是否正在朗讀TTS都被打斷
textToSpeech.stop();
// 關閉,釋放資源
textToSpeech.shutdown();
textToSpeech = null;
}
}
}