如何将内置设置应用于整个应用程序

时间:2018-01-30 12:19:43

标签: android text-to-speech mobile-development

我正在创建一个具有文本到语音的Android应用程序,我希望能够自定义其语速。我已经有了它的代码,但我不知道如何将语速应用于整个应用程序。

这是我为应用程序创建的设置。提前致谢! :d

public float getSpeechRate(){
    int checkedRadioButton = this.radioRate.getCheckedRadioButtonId();
    if (checkedRadioButton == R.id.rate_slow){
         return 0.5f;
    } else if (checkedRadioButton == R.id.rate_normal){
         return 1.0f;
    } else if(checkedRadioButton == R.id.rate_fast){
        return 1.5f;
    }
    return 0;
}

public void setSpeechRate(){
    float speechRate = this.getSpeechRate();
    if(speechRate == 0.5f){
        speakOut("This is a slow speech rate");
    } else if(speechRate == 1.0f){
        speakOut("This is a normal speech rate");
    } else {
        speakOut("This is a fast speech rate");
    }

这就是我调用文本到语音的方式

toSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            Log.e("TTS", "TextToSpeech.OnInit...");
        }
    });

1 个答案:

答案 0 :(得分:2)

执行:

  • 创建"设置"用户选择费率的页面。
  • 按照@brandall
  • 的建议将所选值存储在SharedPreferences中
  • 然后在任何要使用TTS的活动中,执行:

    TextToSpeech tts = TextToSpeechHelper.getTextToSpeech(CurrentActivity.this, customListener);

编辑2

<强> TextToSpeechHelper

 public class TextToSpeechHelper {

    private TextToSpeechHelper() {
        // Prevent the class instantiation
    }

    public static TextToSpeech getTextToSpeech(Context context, @NonNull CustomInitListener listener) {

        final TextToSpeech tts = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                Log.e("TTS", "TextToSpeech.OnInit...");

                if (status == TextToSpeech.SUCCESS) {
                    float rate = getSpeechRate(context);   
                    tts.setSpeechRate(rate);
                    listener.onSuccess();
                } else {
                    listener.onError();
                }
            }
        });


        return tts;
    }

    private static float getSpeechRate(Context context) {
        // Get the value stored in the shared preferences
        // ...
        return storedValue;
    }

    /**
     * Add a custom listener to perform actions when the TextToSpeech is initialized
     */
    public interface CustomInitListener {
        void onSuccess();

        void onError();
    }
}