package com.studio4plus.homerplayer.ui;

import android.content.Context;
import android.speech.tts.TextToSpeech;

import java.util.Locale;

class Speaker implements TextToSpeech.OnInitListener {

    private final Locale locale;
    private final TextToSpeech tts;
    private boolean ttsReady;
    private String pendingSpeech;

    Speaker(Context context) {
        this.locale = context.getResources().getConfiguration().locale;
        this.tts = new TextToSpeech(context, this);
    }

    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            ttsReady = true;
            tts.setLanguage(locale);
            tts.speak(pendingSpeech, TextToSpeech.QUEUE_FLUSH, null);
            pendingSpeech = null;
        }
    }

    public void speak(String text) {
        if (ttsReady) {
            tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        } else {
            pendingSpeech = text;
        }
    }

    public void stop() {
        tts.stop();
        pendingSpeech = null;
    }

    public void shutdown() {
        ttsReady = false;
        tts.shutdown();
    }
}

@@ -107,16 +107,42 @@
 peech;%0A%0A
+import java.util.HashMap;%0A
 import j
@@ -223,72 +223,282 @@
     
-private final Locale locale;%0A    private final TextToSpeech tts;
+// TTS is usually much louder than a regular audio book recording.%0A    private static final String TTS_VOLUME_ADJUSTMENT = %220.5%22;%0A%0A    private final Locale locale;%0A    private final TextToSpeech tts;%0A    private final HashMap%3CString, String%3E speechParams = new HashMap%3C%3E();%0A
 %0A   
@@ -714,16 +714,103 @@
  this);%0A
+        speechParams.put(TextToSpeech.Engine.KEY_PARAM_VOLUME, TTS_VOLUME_ADJUSTMENT);%0A
     %7D%0A%0A 
@@ -1026,36 +1026,44 @@
 ch.QUEUE_FLUSH, 
-null
+speechParams
 );%0A            p
@@ -1215,20 +1215,28 @@
 _FLUSH, 
-null
+speechParams
 );%0A     

Read audio book titles with a softer voice.