Android实现TTS语音播报
生活随笔
收集整理的這篇文章主要介紹了
Android实现TTS语音播报
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
TTS工具類:
public class SystemTTS {private static SystemTTS singleton;private Context mContext;//核心播放對象private TextToSpeech textToSpeech;private boolean isSupport = true;private static final String TAG = "SystemTTS";private boolean isFirstPlay = false;private SystemTTS(Context context) {this.mContext = context.getApplicationContext();textToSpeech = new TextToSpeech(mContext, new TextToSpeech.OnInitListener() {@Overridepublic void onInit(int i) {//textToSpeech的配置init(i);isFirstPlay = false;}});}public static SystemTTS getInstance(Context context) {if (singleton == null) {synchronized (SystemTTS.class) {if (singleton == null) {singleton = new SystemTTS(context);}}}return singleton;}//textToSpeech的配置private void init(int i) {if (i == TextToSpeech.SUCCESS) {int result = textToSpeech.setLanguage(Locale.CHINESE);// 設置音調,值越大聲音越尖(女生),值越小則變成男聲,1.0是常規if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {//系統不支持中文播報isSupport = false;} else {textToSpeech.setPitch(1.0f);textToSpeech.setSpeechRate(1.0f);} }}public boolean play(String text) {boolean ret=false;if (!isSupport) {Toast.makeText(mContext, "TTS不支持", Toast.LENGTH_SHORT).show();ret=true;}if (textToSpeech != null) {if(!isFirstPlay){speak(text);isFirstPlay = true;ret=true;}else{if(!textToSpeech.isSpeaking()){speak(text);ret=true;}}}return ret;}private void speak(String text){textToSpeech.speak(text, TextToSpeech.QUEUE_ADD, null, null);textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {@Overridepublic void onStart(String utteranceId) {Log.d(TAG, "播放開始");}@Overridepublic void onDone(String utteranceId) {Log.d(TAG, "播放結束");}@Overridepublic void onError(String utteranceId) {Log.d(TAG, "播放出錯");}});}public void stop() {if (textToSpeech != null) {textToSpeech.stop();}}public boolean TTsIsSpeeking() {return textToSpeech.isSpeaking();}public void destroy() {stop();if (textToSpeech != null) {textToSpeech.shutdown();}} }有些android手機上面自帶的語音引擎是Pico不支持中文,需要自己下載一個tts引擎,然后在無障礙->文字轉語音TTS->首選引擎設置為自己安裝的引擎。
總結
以上是生活随笔為你收集整理的Android实现TTS语音播报的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电商直播抖音短视频运营创业项目商业计划书
- 下一篇: 2019年个人成长总结