public boolean playing=false;
private void prepareTTSEngine() {
try {
synthesis = SpeechSynthesis.getInstance(this);
synthesis.setSpeechSynthesisEvent(new SpeechSynthesisEvent() {
public void onPlaySuccessful() {
Log.i(TAG, "onPlaySuccessful");
playing=true;
}
public void onPlayStopped() {
Log.i(TAG, "onPlayStopped");
playing=false;
}
public void onPlayFailed(Exception e) {
Log.e(TAG, "onPlayFailed");
e.printStackTrace();
playing=false;
}
public void onPlayStart() {
Log.i(TAG, "onPlayStart");
//playing=true;
}
@Override
public void onPlayCanceled() {
Log.i(TAG, "onPlayCanceled");
playing=false;
}
});
//synthesis.setVoiceType("usenglishfemale1"); // All the values available to you can be found in the developer portal under your account
} catch (InvalidApiKeyException e) {
Log.e(TAG, "Invalid API key\n" + e.getStackTrace());
Toast.makeText(_context, "ERROR: Invalid API key", Toast.LENGTH_LONG).show();
}
}
prepareTTSEngine();
String speech= MapLocationOverlay.mSelectedMapLocation.getShortDesc();
synthesis.setVoiceType("usenglishfemale");
BreakIterator iterator = BreakIterator.getSentenceInstance(Locale.US);
iterator.setText(speech);
int start = iterator.first();
for (int end = iterator.next();end != BreakIterator.DONE; start = end, end = iterator.next()) {
if(speech !=null && speech.substring(start,end).compareTo("")!=0)
{
String sentence_next=speech.substring(start,end);
//set ready flag to true (so isReady returns true)
while(playing==true)
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
synthesis.speak(sentence_next);
} catch (BusyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoNetworkException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
enter code here
}
}
}
I'm using [the iSpeech library's
SpeechSynthesisclass](http://www.ispeech.org/androidsdkdoc/com/ispeech/SpeechSynthesis.html). When I call the
speakmethod in a
for`-loop, passing one sentence at a time, all of the sentences start at once. I guess this is because the method is non-blocking. It's not open-source, so I can't see how it works. How can I make it so that it doesn't start one sentence until the previous sentence is done?
Usually with those kinds of libraries, the code doesn't wait for the sound to stop playing (for good reasons).
From the documentation of your library, it seems that you should listen for
SpeechSynthesisEvent
withPLAY_SUCCESSFUL
before reading the next sentence.If it suits your needs the
javax.speech.synthesis
has a rather simple mechanism to wait until the speech is done, check it out: http://java.sun.com/products/java-media/speech/forDevelopers/jsapi-guide/Synthesis.html