安卓 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("测试到账");
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义