我试图让 Android TTS API 读取我的“话语”,然后调用 onUtteranceCompleted() 监听器,但未成功。我已经注册了我的 TTS 对象,并且它返回 SUCCESS,所以我一生都无法弄清楚为什么我的回调没有被调用。
我尝试过寻求帮助,但似乎其他人也遇到了困难。我错过了一些简单的事情吗?
谢谢你尽你所能的帮助。
package com.test.mytts;
import java.util.HashMap;
import android.app.Activity;
import android.media.AudioManager;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.widget.TextView;
import android.widget.Toast;
public class MyTTS extends Activity implements OnInitListener, OnUtteranceCompletedListener
{
TextView tv;
private TextToSpeech _tts;
@Override
public void onCreate(Bundle savedInstanceState)
{
tv = new TextView(this);
tv.setText("MyTTS: ");
super.onCreate(savedInstanceState);
setContentView(tv);
_tts = new TextToSpeech(this, this);
}
@Override
public void onInit(int status)
{
HashMap<String, String> myHashAlarm = new HashMap<String, String>();
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_NOTIFICATION));
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "test");
if (status == TextToSpeech.SUCCESS)
{
Toast.makeText(this, "Trying to speak...", Toast.LENGTH_SHORT).show();
int result = _tts.setOnUtteranceCompletedListener(this);
tv.append(String.valueOf(result));
_tts.setSpeechRate((float) .5);
_tts.speak("Testing one, two, three", TextToSpeech.QUEUE_ADD, myHashAlarm);
}
else
Toast.makeText(this, "Failed to initialize TTS.", Toast.LENGTH_SHORT).show();
}
@Override
public void onUtteranceCompleted(String utteranceId)
{
Toast.makeText(this, "onUtteranceCompleted", Toast.LENGTH_SHORT).show();
}
@Override
public void onDestroy()
{
super.onDestroy();
_tts.shutdown();
}
}
在tts对象的onInit函数中调用setOnUtteranceCompletedListener。
如果要在调用 onUtteranceCompleted 函数时对 UI 进行任何更改,请在 runOnUIThread 方法中添加代码。
并且请记住在调用 talk() 函数时添加 Hashmap 参数值
例子 :
TextToSpeech tts= new TextToSpeech(context, new OnInitListener() {
@Override
public void onInit(int status) {
mTts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {
@Override
public void onUtteranceCompleted(String utteranceId) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//UI changes
}
});
}
});
}
});
HashMap<String, String> params = new HashMap<String, String>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"stringId");
tts.speak("Text to Speak",TextToSpeech.QUEUE_FLUSH, params);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)