Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use TTS (TextToSpeech) while string has more then 4000 characters in Android

i am developing one module to read text file and play as a voice using TTS. i have successfully integrated TTS in my module. and also reading and speaking first 4000 characters.

i have string with more then 4000 characters, it may have more then 10000 too. at this time i am unable to read file and play using TTS.

i have tried by splitting large string into a small part of string. each string part have 4000 characters.

while i am playing first string part, its working fine as required. but after completed of first string part, i want to start second part immediately. but TTS not starting it.

i am using

int pos = 0;

while(true) {

            String var = "";

            try {
                var = str.substring(pos, 3999);
                pos += 3999;
            } catch(Exception e) {
                var = str.substring(pos, str.length());
                break;
            }

            HashMap<String, String> map = new HashMap<String, String>();
            map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "utteranceId");
            tts.speak(var, TextToSpeech.QUEUE_ADD, map);
        }

i have tried a lot. also searched on web but not getting any good solution.

there is one setOnUtteranceCompletedListener() i think this may be usefull. but how Can anyone please help me. how can i play large text using TTS. or any other technique available?

like image 658
Ajay Avatar asked Mar 13 '15 08:03

Ajay


1 Answers

I also tried to find everywhere but could not find exact answer but definitely got some help. You need to break your long paragraph into small chunks of sentences. You can use the below method to do so.

private void speech(String charSequence) {
    ///
    Pattern re = Pattern.compile("[^.!?\\s][^.!?]*(?:[.!?](?!['\"]?\\s|$)[^.!?]*)*[.!?]?['\"]?(?=\\s|$)", Pattern.MULTILINE | Pattern.COMMENTS);
    Matcher reMatcher = re.matcher(charSequence);
    /////
    int position=0 ;
    int sizeOfChar= charSequence.length();
    String testStri= charSequence.substring(position,sizeOfChar);
    while(reMatcher.find()) {
        String temp="";

        try {

            temp = testStri.substring(charSequence.lastIndexOf(reMatcher.group()), charSequence.indexOf(reMatcher.group())+reMatcher.group().length());
            textToSpeech.speak(temp, TextToSpeech.QUEUE_ADD, null,"speak");


        } catch (Exception e) {
            temp = testStri.substring(0, testStri.length());
            textToSpeech.speak(temp, TextToSpeech.QUEUE_ADD, null);
            break;

        }

    }

}

Just pass your text in this method and it will read your text.

like image 76
Narendra Jadon Avatar answered Oct 27 '22 00:10

Narendra Jadon