Java – How to pause text-to-speech on Android Java

How to pause text-to-speech on Android Java… here is a solution to the problem.

How to pause text-to-speech on Android Java

Currently, I have implemented text-to-speech (TTS) to read books. Since TTS only allows up to 4000 characters (and a book is more than that), I split the book and added each section to the TTS queue. I want to be able to click a button and pause TTS, then resume TTS from where the user left off.

I’ve tried using synthesizeToFile and pausing media file objects, but you can only synthesize one file with less than 4000 characters at a time. I don’t want to store hundreds of media files on a user device for TTS.

I can get TTS to read the book

, I can’t pause without stopping and then have to start TTS from the beginning of the book.

In the code below, I store the entire book in the string bookText.
The TTS engine is a tts variable.

This is how I load the TTS queue:

int position = 0;
int pos = 0;

int sizeOfChar = bookText.length();
String testString = bookText.substring(position,sizeOfChar);

int next = 500;

while(true) {
    String temp = "";

try {
        temp = testString.substring(pos, next);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, temp);
        tts.speak(temp, TextToSpeech.QUEUE_ADD, params);

pos = pos + 500;
        next = next + 500;

}
    catch (Exception e) {
       temp = testString.substring(pos, testString.length());
       tts.speak(temp, TextToSpeech.QUEUE_ADD, null);
       break;
    }
}

This is how I “stop” TTS :

tts.speak("Pausing!", TextToSpeech.QUEUE_FLUSH, null);

Solution

Since the TextToSpeech class doesn’t have a pause/resume method, I recommend doing the following:

1) Divide the book into sentences instead of 500-character blocks. (You can use “.”) parsed as a delimiter).

2) Introduce a “primary index” counter X, which tracks progress: we have sentences # X/total number of sentences.

3) When the user clicks pause, just use the stop() method.

4) When the user clicks resume, continue speaking at the beginning of the interrupted sentence.

In any case, this will give the user a better understanding than literally pausing and resuming the middle of a sentence (book).

Related Problems and Solutions