Search code examples
androidtext-to-speechgoogle-text-to-speech

How can I mute TextToSpeech?


I want the user to be able to turn off the volume of TextToSpeech. I have a button to to this. At the minute I am shutting down the TTS and creating new instance every time the user turns it back on which seems a complete round about way of doing it.

Is there a more efficient way to do this I see no default methods to achieve this:

enter image description here


Solution

  • The solution was to create a bundle and pass this as a third parameter. In the budle you should use params.putFloat(KEY_PARAM_VOLUME, 0.0f); The code explains it better:

    private Bundle params;
    
    public TextToSpeechHelper(Context context) {
        mTTS = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    int result = mTTS.setLanguage(Locale.ENGLISH);
                    params = new Bundle();
    
                    if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                        Log.e("TTS", "Language not supported");
                    }
                } else {
                    Log.e("TTS", "Initialization failed");
                }
            }
        });
    }
    
    public void speakThis(String whatToSay){
        String speech = whatToSay;
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mTTS.speak(speech,TextToSpeech.QUEUE_ADD, params, null);
        } else {
            mTTS.speak(speech, TextToSpeech.QUEUE_ADD, null);
        }
    }
    
    public void mute() {
    
        params.putFloat(KEY_PARAM_VOLUME, 0.0f);
    
    }
    
    public void soundOn() {
    
        params.putFloat(KEY_PARAM_VOLUME, 1.0f);
    
    }