Home » Android » android – How can I exactly implement train platform announcement sound using Text-To-Speech?-Exceptionshub

android – How can I exactly implement train platform announcement sound using Text-To-Speech?-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

Example: (tun tun) Your train/token number is ** 5 0 6 P 0 0 2 3 Q 7**

I want to implement this exact sound in my app. How can I do that. I tried text-to-speech, but it’s not working effectively!?

Please note: Voice sound should not be hardcoded (Otherwise I would have done via raw assests). Token number will be change from server side.

Code:

public class LauncherActivity extends FragmentActivity implements TextToSpeech.OnInitListener {
 private int mStatus;
   private TextToSpeech mTTS;

    private void init() {
        tokenNumber = findViewById(R.id.token_number);
        mTTS = new TextToSpeech(this, this);
        value = 1;
        setHandler();
    }

  private void setTextSound(String textSound, String val) {
    if (mStatus == TextToSpeech.SUCCESS) {
        int result = mTTS.setLanguage(Locale.ENGLISH);

        if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Logger.d("Language not supported");
        } else {
            String freshString = val.replaceAll("[-+.^:,]", "");

            mTTS.setPitch(1f);
            mTTS.setSpeechRate(0.8f);
            char[] ch = freshString.toCharArray();

            // Printing array
            mTTS.speak(textSound, TextToSpeech.QUEUE_ADD, null, null);
            for (char c : ch) {
                mTTS.setSpeechRate(0.4f);
                mTTS.speak(String.valueOf(c), TextToSpeech.QUEUE_ADD, null, null);
            }


        }

    } else {
        Logger.d("Something went wrong. Please try again later");
    }
}

If possible, suggest me without use of any library.

How to&Answers:

Change your setTextSound method to following

private void setTextSound(String textSound) {
    if (mStatus == TextToSpeech.SUCCESS) {
        int result = mTTS.setLanguage(Locale.ENGLISH);

        if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Logger.d("Language not supported");
        } else {
            String freshString = textSound.replaceAll("[-+.^:,]","");

            mTTS.setPitch(1f);
            mTTS.setSpeechRate(1f);
            char[] ch = freshString.toCharArray();

            // Printing array
            for (char c : ch) {
                mTTS.speak(String.valueOf(c)  , TextToSpeech.QUEUE_ADD, null);
            }


        }

    } else {
        Logger.d("Something went wrong. Please try again later");
    }
} 

Let me know if it works