我正在尝试将onutterance -progresslistener放在tts上。我已经在Stackoverflow上遇到了其他相关问题,并遵循了它们。但是,即使将话语ID字符串通过hashmap或bundle(由于Hashmap在API21之后被弃用(之后,TusteranceProgressListener也没有被调用。我已经用吐司来验证,但是没有吐司输出。我正在获取音频输出,但无法获得ProgressListener的工作。
@Override
public void onInit(int initStatus) {
if (initStatus == TextToSpeech.SUCCESS) {
myTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
Toast.makeText(InvisibleActivity.this,"listener Started",Toast.LENGTH_SHORT).show();
}
@Override
public void onDone(String utteranceId) {
if (utteranceId.equals("utteranceId")) {
myTTS.stop();
Toast.makeText(InvisibleActivity.this,"mytts stopped",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(String utteranceId) {
}
});
myTTS.setLanguage(Locale.US);
} else if (initStatus == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry,Text To speech not supported", Toast.LENGTH_SHORT).show();
}
Bundle bundle = new Bundle();
bundle.putString(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"utteranceId");
myTTS.speak(outText, TextToSpeech.QUEUE_FLUSH, bundle,null);
chan();
}
我使用过的hashmap代码(带有deftected speps(((是:
HashMap<String,String> params = new HashMap<>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"utteranceId");
myTTS.speak(outText,TextToSpeech.QUEUE_FLUSH, params);
我已经尝试了QUEUE_ADD
和QUEUE_FLUSH
,但结果是相同的。
这是因为它在另一个线程上起作用。您需要使用RunonuitHread来使其起作用:
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onStart(String s) {
final String keyword = s;
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "Started " + keyword, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onDone(String s) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "Done ", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onError(String s) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "Error ", Toast.LENGTH_SHORT).show();
}
});
}
});
确保在speak
方法之前调用此方法。