安卓 TextToSpeech: speak failed: not bound to TTS engine
关于语音播报一段时间没有使用系统返回 speak failed: not bound to TTS engine 错误解决办法
通过textToSpeech?.speak 返回参数判断播放是否成功如果返回-1需要重新实例化TextToSpeech。
完整代码:
SystemTTS
package com.dzw.pushlib.audio import android.content.Context import android.speech.tts.TextToSpeech import android.speech.tts.UtteranceProgressListener import android.util.Log import java.util.* class SystemTTS private constructor(private val context: Context) : UtteranceProgressListener(), TTS { // 系统语音播报类 private var textToSpeech: TextToSpeech? = null private var isSuccess = false init { initSpeech() } /** * 初始化语音播报 */ private fun initSpeech(onSuccess: () -> Unit = {}) { textToSpeech = TextToSpeech(context) { statue: Int -> try { //系统语音初始化成功 if (statue == TextToSpeech.SUCCESS) { isSuccess = true val result = textToSpeech!!.setLanguage(Locale.CHINA) textToSpeech!!.setOnUtteranceProgressListener(this) if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { //系统不支持中文播报 isSuccess = false return@TextToSpeech } onSuccess() } else { isSuccess = false } } catch (e: Exception) { e.printStackTrace() } } } override fun playText(playText: String) { // 设置音调,值越大声音越尖(女生),值越小则变成男声,1.0是常规 textToSpeech?.setPitch(1.0f) textToSpeech?.setSpeechRate(1.0f) val status = textToSpeech?.speak(playText, TextToSpeech.QUEUE_ADD, null, null) Log.e("wade", "$status") if (status == TextToSpeech.ERROR) { initSpeech { // 设置音调,值越大声音越尖(女生),值越小则变成男声,1.0是常规 playText(playText) } } } override fun stopSpeak() { if (textToSpeech != null) { textToSpeech?.stop() } } override fun onStart(utteranceId: String) {} override fun onDone(utteranceId: String) {} override fun onError(utteranceId: String) {} companion object { private var singleton: SystemTTS? = null @JvmStatic fun getInstance(context: Context): TTS? { if (singleton == null) { synchronized(SystemTTS::class.java) { if (singleton == null) { singleton = SystemTTS(context) } } } return singleton } } }
TTS
public interface TTS { void playText(String playText); void stopSpeak(); }
使用方法:
SystemTTS.getInstance(context).playText("测试到账");