Android系統本身自帶的語音引擎不支持中文,所以需要依賴 如 科大訊飛、度祕 等,類似語音引擎纔可以。
三步:
1:安裝語音引擎。 安裝包百度找一下。安裝到需要播報的機子上
如果沒找到的話,這裏有:https://download.csdn.net/download/qq_39731011/15047992 //爲了防止你們懶得自己找,特設5C幣門檻
2:設置採用該引擎: 設置— 語音和輸入法— 文字轉語音(TTS)輸出— 首選引擎—選擇你安裝的引擎
3:將以下工具類複製到項目中,一行代碼直接用
一行代碼調用:
SpeechUtils.getInstance(this).speakText("語音播報的內容");
/**
* Created by Xinghai.Zhao on 2021/2/4
* android自帶語音識別工具,如果要支持中文需要配合其他語音引擎
*/
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.text.TextUtils;
import java.util.Locale;
public class SpeechUtils {
private Context context;
private static final String TAG = "SpeechUtils";
private static volatile SpeechUtils singleton;
private TextToSpeech textToSpeech; // TTS對象
// private boolean isOld;
public static SpeechUtils getInstance(Context context) {
if (singleton == null) {
synchronized (SpeechUtils.class) {
if (singleton == null) {
singleton = new SpeechUtils(context);
}
}
}
return singleton;
}
public SpeechUtils(Context context) {
this.context = context;
speakText(null);
}
/**
* 關閉 語音合成
*/
public void shutdown(){
if(textToSpeech!=null){
textToSpeech.stop();
textToSpeech.shutdown();
textToSpeech = null;
}
}
/**
* 第二個參數queueMode用於指定發音隊列模式,兩種模式選擇
* (1)TextToSpeech.QUEUE_FLUSH:該模式下在有新任務時候會清除當前語音任務,執行新的語音任務
* (2)TextToSpeech.QUEUE_ADD:該模式下會把新的語音任務放到語音任務之後,
* @param text
*/
public void speakText(String text) {
if(textToSpeech==null){
textToSpeech = new TextToSpeech(context, 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);
/*if(result != TextToSpeech.LANG_COUNTRY_AVAILABLE
&& result != TextToSpeech.LANG_AVAILABLE){
Toast.makeText(context, "TTS暫時不支持這種語音的朗讀!",
Toast.LENGTH_LONG).show();
}else {
textToSpeech.setPitch(1.0f);// 設置音調,值越大聲音越尖(女生),值越小則變成男聲,1.0是常規
textToSpeech.setSpeechRate(1.0f);
}*/
}
}
});
}
if(!TextUtils.isEmpty(text)){
textToSpeech.speak(text,TextToSpeech.QUEUE_ADD, null);
}
}
}