javaandroidtext-to-speech

Control the volume on TextToSpeech function call


Hi guys

I've been looking around but cannot seem to find a suitable answer to integrate into my function. I am basically using the following code currently:

    private void sayHello(String timeString) {

    textToSpeech.speak(timeString,
    TextToSpeech.QUEUE_FLUSH,
    null);
}

This code works fine but it's too loud and it can only be controlled by the volume of the device itself. I want to be able to adjust/hardcode/be able to use spinner to control the volume of the TTS but cannot seem to do so accordingly.

Is this functionality available for this library? Is it achievable?
I've also tried to implement the following into my code:

KEY_PARAM_VOLUME

However, I cannot see any examples of this being used and it's showing up with the error to create a function. Any advice?


Solution

  • public class MainActivity extends AppCompatActivity {
    
        int androidAPILevel = android.os.Build.VERSION.SDK_INT;
        TextToSpeech tts;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
                @Override
                public void onInit(int i) {
                    start();
                }
            });
        }
    
        private void start() {
            if (androidAPILevel < 21) {
                HashMap<String,String> params = new HashMap<>();
                params.put(TextToSpeech.Engine.KEY_PARAM_VOLUME, "0.5"); // change the 0.5 to any value from 0-1 (1 is default)
                tts.speak("This is a volume test.", TextToSpeech.QUEUE_FLUSH, params);
            } else { // android API level is 21 or higher...
                Bundle params = new Bundle();
                params.putFloat(TextToSpeech.Engine.KEY_PARAM_VOLUME, 0.5f); // change the 0.5f to any value from 0f-1f (1f is default)
                tts.speak("This is a volume test.", TextToSpeech.QUEUE_FLUSH, params, null);
            }
        }
    }