Search code examples
androidarraysstringtext-to-speechandroid-button

TextToSpeech With a String Array


I tried to follow this question here String array incrementing each string but it didn't want to work, What im trying to do is when the button is clicked increment what the TextToSpeech voice is going to say by incrementing the string. therefore start at string 0, then 1 to 2 to 3 to 4 ect and loop back around. heres the code

String Array Code

            String [] speakLetters = { "Letter A for Ant", "Letter b for Bat", "Letter C for Cat" ....... , "Letter Z for zoo"};

The array is laid out just fine its just not working when trying to increment. it either says its just ANT for the first one and never increments or it freezes if I change the code.

Code for trying to increment the array

                mNextBtn.setOnClickListener(new OnClickListener() {
                        int cIndex = 0;
                            int stringLength = speakLetters.length;
                            String speakNow = speakLetters[stringLength];
                            cIndex = (cIndex++); // I also tried here cIndex = (cIndex + 1) % stringLength;
                            tts.speak(speakNow, TextToSpeech.QUEUE_FLUSH, null);

                        mNextBtn.setEnabled(mSCanvas.isUndoable());
                        }

Yes I am writing this to an scanvas I wanted to include that just incase that could be the problem even though I doubt it is.

What am I doing wrong?


Solution

  • Declare cIndex variable as class member outside your click listener block:

    int cIndex = 0;
    

    and then modify click handler code:

    mNextBtn.setOnClickListener(new OnClickListener() {
          String speakNow = speakLetters[cIndex];
          tts.speak(speakNow, TextToSpeech.QUEUE_FLUSH, null);
    
          cIndex++;
          cIndex %= speakLetters.length;
    
          mNextBtn.setEnabled(mSCanvas.isUndoable());
     });