1.首先去讯飞语记官网下载并安装APP:
http://www.iyuji.cn/iyuji/home
2.设置语音引擎:
设置==>语言和输入法==>文字转语音(TTS)输出==>首选引擎
3.在代码中使用:
import android.content.Context; import android.speech.tts.TextToSpeech; import android.util.Log; import java.util.Locale; public class SystemTTS { private static final String TAG = "SystemTTS"; private static SystemTTS instance; private TextToSpeech textToSpeech; private boolean isSupport = true; private SystemTTS(Context context) { textToSpeech = new TextToSpeech(context, new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { int result = textToSpeech.setLanguage(Locale.CHINA); textToSpeech.setPitch(1.0f); // 设置音调 textToSpeech.setSpeechRate(1.0f); // 设置语速 if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { isSupport = false; Log.i(TAG, "系统不支持中文语音播报"); } } } }); } public static SystemTTS getInstance(Context context) { if (instance == null) { instance = new SystemTTS(context); } return instance; } public void speak(String text) { if (!isSupport) { return; } if (textToSpeech != null) { textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null); } } public void destroy() { if (textToSpeech != null) { textToSpeech.stop(); textToSpeech.shutdown(); } instance = null; } }
4.控制台报错:speak failed: not bound to TTS engine
只需要在AndroidManifest.xml文件中增加<queries>标签即可
... <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/> <queries> <intent> <action android:name="android.intent.action.TTS_SERVICE" /> </intent> </queries> <application ...
参考链接: