我遇到了些困难... 我想通过TTS语音功能和屏幕上的文本,逐句朗读几个句子。
我已经准备好了TextView区域,但是我无法将它们组合在一起。要么它会朗读所有的句子并只显示最后一个,要么它只会显示和朗读第一句话。
有人知道我该如何实现这个目标吗?
我遇到了些困难... 我想通过TTS语音功能和屏幕上的文本,逐句朗读几个句子。
我已经准备好了TextView区域,但是我无法将它们组合在一起。要么它会朗读所有的句子并只显示最后一个,要么它只会显示和朗读第一句话。
有人知道我该如何实现这个目标吗?
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
}
@Override
public void onDone(String utteranceId) {
LettersActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
// Do something on UI thread
}
});
}
@Override
public void onError(String utteranceId) {
Log.e(TAG, "error on " + utteranceId);
}
});
public void speak(String message){
tts.speak(message, TextToSpeech.QUEUE_FLUSH, null);
while (tts.isSpeaking()){
System.Out.Println("Do something or nothing while speaking..")
}
}
boolean speakingEnd = tts.isSpeaking();
do{
speakingEnd = tts.isSpeaking();
} while (speakingEnd);
//Continue with code
试试这个
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener{
private boolean initialized;
private String queuedText;
private String TAG = "TTS";
private TextToSpeech tts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this /* context */, this /* listener */);
tts.setOnUtteranceProgressListener(mProgressListener);
speak("hello world");
}
public void speak(String text) {
if (!initialized) {
queuedText = text;
return;
}
queuedText = null;
setTtsListener(); // no longer creates a new UtteranceProgressListener each time
HashMap<String, String> map = new HashMap<String, String>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "MessageId");
tts.speak(text, TextToSpeech.QUEUE_ADD, map);
}
private void setTtsListener() {
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
initialized = true;
tts.setLanguage(Locale.ENGLISH);
if (queuedText != null) {
speak(queuedText);
}
}
}
private abstract class runnable implements Runnable {
}
private UtteranceProgressListener mProgressListener = new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
} // Do nothing
@Override
public void onError(String utteranceId) {
} // Do nothing.
@Override
public void onDone(String utteranceId) {
new Thread()
{
public void run()
{
MainActivity.this.runOnUiThread(new runnable()
{
public void run()
{
Toast.makeText(getBaseContext(), "TTS Completed", Toast.LENGTH_SHORT).show();
}
});
}
}.start();
}
};
}