我已经能够从一个活动中运行TTS但是当我尝试从一个服务执行相同的代码时,它给我的消息是TTS引擎已初始化但没有说话。
有人在任何时候都遇到过同样的问题吗?
public void onCreate() {
super.onCreate();
tts = new TextToSpeech(this, this //TextToSpeech.OnInitListener);
timer.scheduleAtFixedRate( new TimerTask()
{ // In timer
public void run() {
//On some condition
tts.speak("thank you", TextToSpeech.QUEUE_ADD, null);
}, 0, 60000);
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Toast.makeText(BackgroundProcessforTimecheck.this,
"Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
}
else if (status == TextToSpeech.ERROR) {
Toast.makeText(BackgroundProcessforTimecheck.this,
"Error occurred while initializing Text-To-Speech engine", Toast.LENGTH_LONG).show();
}
}
有人可以帮忙吗?
答案 0 :(得分:6)
我遇到了同样的问题并以这种方式解决了这个问题: 在单独的类中实例化TextToSpeech对象(在我的情况下,我还使用工厂来检查Android版本是否至少是Donut)和重用它(请参阅方法init(上下文上下文))。请注意,onInit(int status)远未准备好发布。
服务:
@Override
public void onStart(Intent intent, int startId) {
Context context = getApplicationContext();
TtsProviderFactory ttsProviderImpl = TtsProviderFactory.getInstance();
if (ttsProviderImpl != null) {
ttsProviderImpl.init(context);
ttsProviderImpl.say("hope that helps);
}}
厂:
public abstract class TtsProviderFactory {
public abstract void say(String sayThis);
public abstract void init(Context context);
public abstract void shutdown();
private static TtsProviderFactory sInstance;
public static TtsProviderFactory getInstance() {
if (sInstance == null) {
int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
if (sdkVersion < Build.VERSION_CODES.DONUT) {
return null;
}
try {
String className = "TtsProviderImpl";
Class<? extends TtsProviderFactory> clazz =
Class.forName(TtsProviderFactory.class.getPackage().getName() + "." + className)
.asSubclass(TtsProviderFactory.class);
sInstance = clazz.newInstance();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
return sInstance;
}}
实现:
public class TtsProviderImpl extends TtsProviderFactory implements TextToSpeech.OnInitListener {
private TextToSpeech tts;
public void init(Context context) {
if (tts == null) {
tts = new TextToSpeech(context, this);
}
}
@Override
public void say(String sayThis) {
tts.speak(sayThis, TextToSpeech.QUEUE_FLUSH, null);
}
@Override
public void onInit(int status) {
Locale loc = new Locale("de", "", "");
if (tts.isLanguageAvailable(loc) >= TextToSpeech.LANG_AVAILABLE) {
tts.setLanguage(loc);
}
}
public void shutdown() {
tts.shutdown();
}}
答案 1 :(得分:0)
您是否在设备中安装了TTS引擎?我也遇到了同样的问题同样的问题。但后来我发现我必须将TTS引擎安装到我的真实设备上,并且可以在Play商店中使用。