0

I want my application speak a sentence "Hello, If Your Case Is Emergency CALL 911" when the activity starting, but i cannot do that.

i had used the following code:

public class home extends AppCompatActivity  implements TextToSpeech.OnInitListener {
    Button Signin , listButton,Speak;
    EditText Text;
    Button mSpeak;
    private TextToSpeech mTTS;
    protected static final int RESULT_SPEECH = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

      //  TTS 
        mTTS = new TextToSpeech(this, this);
        mSpeak =  (Button) findViewById(R.id.mSpeak);
        mSpeak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                speak("Hello, If Your Case Is Emergency CALL 911 , IF not Continue");
            }
        });

        speak("Hello, If Your Case Is Emergency CALL 911 , IF not Continue");
    }


    public void speak(String str) {
          mTTS.speak(str, TextToSpeech.QUEUE_FLUSH, null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTTS.shutdown();
    }

    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            int result = mTTS.setLanguage(Locale.UK);
            mTTS.setPitch(0.8f);
            mTTS.setSpeechRate(1.1f);

            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("TTS", "Language not supported");
            } else {
                mSpeak.setEnabled(true);
            }
        } else {
            Log.e("TTS", "Initialization failed");
        }
    }
}

in the previous code, when i try to run "TextToSpeech" using the "mSpeak" Button it work correctly. however, when run it on "onCreate" it not work.

1 Answers1

0
TextToSpeech mTTS = new TextToSpeech(this, this);
mTTS.setLanguage(Locale.US);

Please initialised mTTS like above before you called mTTS.speak()

Android Dev
  • 1,496
  • 1
  • 13
  • 25
  • error: incompatible types: home cannot be converted to OnInitListener – LaiLa AlQam Sep 30 '19 at 10:00
  • you need to implement `TextToSpeech.OnInitListener` in current class – Android Dev Sep 30 '19 at 10:04
  • I use mTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener() { – LaiLa AlQam Sep 30 '19 at 10:21
  • now havent erorr but cant listen any thing >>> lets my code -----> protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); mTTS = new TextToSpeech(this, this); mTTS.setLanguage(Locale.US); mTTS.setPitch(0.8f); mTTS.setSpeechRate(1.1f); mTTS.speak("Hello, If Your Case Is Emergency CALL 911 , IF not Continue", TextToSpeech.QUEUE_FLUSH, null); – LaiLa AlQam Sep 30 '19 at 10:48