neh*_*eha 0 android text-to-speech
我已经能够从一个活动中运行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();
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙吗?
小智 6
我遇到了同样的问题并以这种方式解决了:在一个单独的类中实例化TextToSpeech对象(在我的情况下,我还使用Factory来检查Android版本是否至少是Donut)并重用它(请参阅方法init(Context context)) .请注意,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);
}}
Run Code Online (Sandbox Code Playgroud)
厂:
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;
}}
Run Code Online (Sandbox Code Playgroud)
执行:
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();
}}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5718 次 |
| 最近记录: |