Search in sources :

Example 1 with OnInitListener

use of android.speech.tts.TextToSpeech.OnInitListener in project LibreraReader by foobnix.

the class DragingDialogs method textToSpeachDialog.

public static void textToSpeachDialog(final FrameLayout anchor, final DocumentController controller, final String textToRead) {
    if (TTSEngine.get().hasNoEngines()) {
        Urls.openTTS(controller.getActivity());
        return;
    }
    DragingPopup dialog = new DragingPopup(R.string.text_to_speech, anchor, 300, 440) {

        @Override
        @SuppressLint("NewApi")
        public View getContentView(LayoutInflater inflater) {
            final Activity activity = controller.getActivity();
            final View view = inflater.inflate(R.layout.dialog_tts, null, false);
            final TextView ttsPage = (TextView) view.findViewById(R.id.ttsPage);
            // ttsPage.setText(activity.getString(R.string.page) + " " +
            // controller.getCurentPageFirst1());
            final TextView textEngine = (TextView) view.findViewById(R.id.ttsEngine);
            final TextView textDebug = (TextView) view.findViewById(R.id.textDebug);
            final TextView timerTime = (TextView) view.findViewById(R.id.timerTime);
            final TextView timerStart = (TextView) view.findViewById(R.id.timerStart);
            timerTime.setText(AppState.get().ttsTimer + " " + controller.getString(R.string.minutes).toLowerCase(Locale.US));
            timerTime.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    final PopupMenu popupMenu = new PopupMenu(v.getContext(), v);
                    for (int i = 15; i <= 300; i += 15) {
                        final int number = i;
                        popupMenu.getMenu().add("" + i).setOnMenuItemClickListener(new OnMenuItemClickListener() {

                            @Override
                            public boolean onMenuItemClick(MenuItem item) {
                                AppState.get().ttsTimer = number;
                                timerTime.setText(AppState.get().ttsTimer + " " + controller.getString(R.string.minutes).toLowerCase(Locale.US));
                                return false;
                            }
                        });
                    }
                    popupMenu.show();
                }
            });
            timerStart.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (TempHolder.get().timerFinishTime == 0) {
                        TempHolder.get().timerFinishTime = System.currentTimeMillis() + AppState.get().ttsTimer * 60 * 1000;
                    } else {
                        TempHolder.get().timerFinishTime = 0;
                    }
                    timerStart.setText(TempHolder.get().timerFinishTime == 0 ? R.string.start : R.string.cancel);
                    ttsPage.setText(TempHolder.get().timerFinishTime == 0 ? "" : controller.getString(R.string.reading_will_be_stopped) + " " + DateFormat.getTimeFormat(activity).format(TempHolder.get().timerFinishTime));
                }
            });
            timerStart.setText(TempHolder.get().timerFinishTime == 0 ? R.string.start : R.string.cancel);
            ttsPage.setText(TempHolder.get().timerFinishTime == 0 ? "" : controller.getString(R.string.reading_will_be_stopped) + " " + DateFormat.getTimeFormat(activity).format(TempHolder.get().timerFinishTime));
            TTSEngine.get().getTTS(new OnInitListener() {

                @Override
                public void onInit(int status) {
                    textEngine.setText(TTSEngine.get().getCurrentEngineName());
                    TxtUtils.underlineTextView(textEngine);
                }
            });
            textEngine.setText(TTSEngine.get().getCurrentEngineName());
            TxtUtils.underlineTextView(textEngine);
            textEngine.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    PopupMenu menu = new PopupMenu(v.getContext(), v);
                    List<EngineInfo> engines = TTSEngine.get().getTTS().getEngines();
                    for (final EngineInfo eInfo : engines) {
                        final String name = TTSEngine.engineToString(eInfo);
                        menu.getMenu().add(name).setOnMenuItemClickListener(new OnMenuItemClickListener() {

                            @Override
                            public boolean onMenuItemClick(MenuItem item) {
                                textEngine.setText(name);
                                TTSEngine.get().setTTSWithEngine(eInfo.name);
                                TxtUtils.underlineTextView(textEngine);
                                return false;
                            }
                        });
                    }
                    menu.show();
                }
            });
            view.findViewById(R.id.ttsSettings).setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    try {
                        TTSEngine.get().stop();
                        Intent intent = new Intent();
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        if (Build.VERSION.SDK_INT >= 14) {
                            intent.setAction("com.android.settings.TTS_SETTINGS");
                        } else {
                            intent.addCategory(Intent.CATEGORY_LAUNCHER);
                            intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.TextToSpeechSettings"));
                        }
                        activity.startActivity(intent);
                    } catch (Exception e) {
                        Toast.makeText(activity, e.getMessage(), Toast.LENGTH_LONG).show();
                        LOG.e(e);
                    }
                }
            });
            view.findViewById(R.id.onPlay).setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    TTSService.playBookPage(controller.getCurentPageFirst1() - 1, controller.getCurrentBook().getPath(), "", controller.getBookWidth(), controller.getBookHeight(), AppState.get().fontSizeSp);
                }
            });
            view.findViewById(R.id.onPause).setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    TTSEngine.get().stop();
                    TTSNotification.hideNotification();
                }
            });
            view.findViewById(R.id.onPause).setOnLongClickListener(new OnLongClickListener() {

                @Override
                public boolean onLongClick(View v) {
                    textDebug.setVisibility(View.VISIBLE);
                    return true;
                }
            });
            final SeekBar seekBarSpeed = (SeekBar) view.findViewById(R.id.seekBarSpeed);
            seekBarSpeed.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                }

                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    if (fromUser) {
                        AppState.get().ttsSpeed = (float) progress / 100;
                    }
                }
            });
            final SeekBar seekBarPitch = (SeekBar) view.findViewById(R.id.seekBarPitch);
            seekBarPitch.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                }

                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    if (fromUser) {
                        AppState.get().ttsPitch = (float) progress / 100;
                    }
                }
            });
            seekBarPitch.setProgress((int) (AppState.get().ttsPitch * 100));
            seekBarSpeed.setProgress((int) (AppState.get().ttsSpeed * 100));
            final AudioManager audioManager = (AudioManager) activity.getSystemService(Context.AUDIO_SERVICE);
            final SeekBar seekVolume = (SeekBar) view.findViewById(R.id.seekVolume);
            seekVolume.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
            seekVolume.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
            seekVolume.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                }

                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    if (fromUser) {
                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
                    }
                }
            });
            TxtUtils.underlineTextView((TextView) view.findViewById(R.id.restore_defaults)).setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    AlertDialogs.showOkDialog(controller.getActivity(), controller.getString(R.string.restore_defaults_full), new Runnable() {

                        @Override
                        public void run() {
                            seekBarPitch.setProgress(100);
                            seekBarSpeed.setProgress(100);
                            AppState.get().ttsPitch = (float) 1.0;
                            AppState.get().ttsSpeed = (float) 1.0;
                            TTSEngine.get().shutdown();
                            TTSEngine.get().getTTS();
                            textEngine.setText(TTSEngine.get().getCurrentEngineName());
                            TxtUtils.underlineTextView(textEngine);
                        }
                    });
                }
            });
            // 
            CheckBox notificationOngoing = (CheckBox) view.findViewById(R.id.notificationOngoing);
            notificationOngoing.setChecked(AppState.get().notificationOngoing);
            notificationOngoing.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
                    AppState.get().notificationOngoing = isChecked;
                    TTSNotification.hideNotification();
                    TTSNotification.showLast();
                }
            });
            CheckBox stopReadingOnCall = (CheckBox) view.findViewById(R.id.stopReadingOnCall);
            stopReadingOnCall.setChecked(AppState.get().stopReadingOnCall);
            stopReadingOnCall.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
                    AppState.get().stopReadingOnCall = isChecked;
                }
            });
            view.findViewById(R.id.ttsSkeakToFile).setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    AlertDialog.Builder dialog = new AlertDialog.Builder(controller.getActivity());
                    dialog.setTitle(R.string.speak_into_file_wav_);
                    View inflate = LayoutInflater.from(v.getContext()).inflate(R.layout.dialog_tts_wav, null, false);
                    final TextView ttsSpeakPath = (TextView) inflate.findViewById(R.id.ttsSpeakPath);
                    final TextView progressText = (TextView) inflate.findViewById(R.id.progressText);
                    final ProgressBar progressBar1 = (ProgressBar) inflate.findViewById(R.id.progressBar1);
                    final Button start = (Button) inflate.findViewById(R.id.start);
                    final Button stop = (Button) inflate.findViewById(R.id.stop);
                    progressBar1.setVisibility(View.GONE);
                    progressText.setText("");
                    ttsSpeakPath.setText(Html.fromHtml("<u>" + AppState.get().ttsSpeakPath + "/<b>" + controller.getCurrentBook().getName() + "</b></u>"));
                    ttsSpeakPath.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            ChooserDialogFragment.chooseFolder((FragmentActivity) controller.getActivity(), AppState.get().ttsSpeakPath).setOnSelectListener(new ResultResponse2<String, Dialog>() {

                                @Override
                                public boolean onResultRecive(String nPath, Dialog dialog) {
                                    AppState.get().ttsSpeakPath = nPath;
                                    ttsSpeakPath.setText(Html.fromHtml("<u>" + AppState.get().ttsSpeakPath + "/<b>" + controller.getCurrentBook().getName() + "</b></u>"));
                                    dialog.dismiss();
                                    return false;
                                }
                            });
                        }
                    });
                    final ResultResponse<String> info = new ResultResponse<String>() {

                        @Override
                        public boolean onResultRecive(final String result) {
                            controller.getActivity().runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    progressText.setText(result);
                                }
                            });
                            return false;
                        }
                    };
                    stop.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            TempHolder.isRecordTTS = false;
                            progressBar1.setVisibility(View.GONE);
                        }
                    });
                    start.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            if (!TempHolder.isRecordTTS) {
                                TempHolder.isRecordTTS = true;
                                progressBar1.setVisibility(View.VISIBLE);
                                TTSEngine.get().speakToFile(controller, info);
                            }
                        }
                    });
                    dialog.setView(inflate);
                    dialog.setNegativeButton(R.string.close, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            TempHolder.isRecordTTS = false;
                        }
                    });
                    AlertDialog create = dialog.create();
                    create.setOnDismissListener(new OnDismissListener() {

                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            TempHolder.isRecordTTS = false;
                        }
                    });
                    create.show();
                }
            });
            return view;
        }
    };
    dialog.setOnCloseListener(new Runnable() {

        @Override
        public void run() {
            AppState.get().save(controller.getActivity());
        }
    });
    dialog.show("TTS");
}
Also used : AlertDialog(android.app.AlertDialog) ResultResponse(com.foobnix.android.utils.ResultResponse) DialogInterface(android.content.DialogInterface) OnMenuItemClickListener(android.view.MenuItem.OnMenuItemClickListener) FragmentActivity(android.support.v4.app.FragmentActivity) HorizontalViewActivity(com.foobnix.pdf.search.activity.HorizontalViewActivity) Activity(android.app.Activity) OnSeekBarChangeListener(android.widget.SeekBar.OnSeekBarChangeListener) EngineInfo(android.speech.tts.TextToSpeech.EngineInfo) AudioManager(android.media.AudioManager) Button(android.widget.Button) CompoundButton(android.widget.CompoundButton) Dialog(android.app.Dialog) ProgressDialog(android.app.ProgressDialog) ColorsDialog(com.foobnix.pdf.info.widget.ColorsDialog) AlertDialog(android.app.AlertDialog) FontDialog(com.foobnix.pdf.info.widget.FontDialog) TapZoneDialog(com.foobnix.pdf.info.widget.TapZoneDialog) OnLongClickListener(android.view.View.OnLongClickListener) TextView(android.widget.TextView) ArrayList(java.util.ArrayList) List(java.util.List) ComponentName(android.content.ComponentName) ProgressBar(android.widget.ProgressBar) OnInitListener(android.speech.tts.TextToSpeech.OnInitListener) OnCheckedChangeListener(android.widget.CompoundButton.OnCheckedChangeListener) SeekBar(android.widget.SeekBar) OnDismissListener(android.content.DialogInterface.OnDismissListener) MenuItem(android.view.MenuItem) Intent(android.content.Intent) ImageView(android.widget.ImageView) RecyclerView(android.support.v7.widget.RecyclerView) GridView(android.widget.GridView) View(android.view.View) AdapterView(android.widget.AdapterView) TextView(android.widget.TextView) ListView(android.widget.ListView) AbsListView(android.widget.AbsListView) SuppressLint(android.annotation.SuppressLint) FragmentActivity(android.support.v4.app.FragmentActivity) CheckBox(android.widget.CheckBox) LayoutInflater(android.view.LayoutInflater) OnClickListener(android.view.View.OnClickListener) CompoundButton(android.widget.CompoundButton) PopupMenu(android.widget.PopupMenu)

Example 2 with OnInitListener

use of android.speech.tts.TextToSpeech.OnInitListener in project Osmand by osmandapp.

the class TTSCommandPlayerImpl method initializeEngine.

private void initializeEngine(final Context ctx, final Activity act) {
    if (mTtsContext != ctx) {
        internalClear();
    }
    if (mTts == null) {
        mTtsContext = ctx;
        ttsVoiceStatus = "";
        ttsVoiceUsed = "";
        ttsRequests = 0;
        final float speechRate = cSpeechRate;
        final String[] lsplit = (language + "____.").split("[\\_\\-]");
        // constructor supports lang_country_variant
        Locale newLocale0 = new Locale(lsplit[0], lsplit[1], lsplit[2]);
        // #3344: Try Locale builder instead of constructor (only available from API 21). Also supports script (for now supported as trailing x_x_x_Scrp)
        if (android.os.Build.VERSION.SDK_INT >= 21) {
            try {
                newLocale0 = new Locale.Builder().setLanguage(lsplit[0]).setScript(lsplit[3]).setRegion(lsplit[1]).setVariant(lsplit[2]).build();
            } catch (RuntimeException e) {
            // Falls back to constructor
            }
        }
        final Locale newLocale = newLocale0;
        mTts = new TextToSpeech(ctx, new OnInitListener() {

            @Override
            public void onInit(int status) {
                if (status != TextToSpeech.SUCCESS) {
                    ttsVoiceStatus = "NO INIT SUCCESS";
                    internalClear();
                } else if (mTts != null) {
                    speechAllowed = true;
                    switch(mTts.isLanguageAvailable(newLocale)) {
                        case TextToSpeech.LANG_MISSING_DATA:
                            if (isSettingsActivity(act)) {
                                AlertDialog.Builder builder = createAlertDialog(R.string.tts_missing_language_data_title, R.string.tts_missing_language_data, new IntentStarter(act, TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA), act);
                                builder.show();
                            }
                            ttsVoiceStatus = newLocale.getDisplayName() + ": LANG_MISSING_DATA";
                            ttsVoiceUsed = getVoiceUsed();
                            break;
                        case TextToSpeech.LANG_AVAILABLE:
                            ttsVoiceStatus = newLocale.getDisplayName() + ": LANG_AVAILABLE";
                        case TextToSpeech.LANG_COUNTRY_AVAILABLE:
                            ttsVoiceStatus = "".equals(ttsVoiceStatus) ? newLocale.getDisplayName() + ": LANG_COUNTRY_AVAILABLE" : ttsVoiceStatus;
                        case TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE:
                            try {
                                mTts.setLanguage(newLocale);
                            } catch (Exception e) {
                                e.printStackTrace();
                                mTts.setLanguage(Locale.getDefault());
                            }
                            if (speechRate != 1) {
                                mTts.setSpeechRate(speechRate);
                            }
                            ttsVoiceStatus = "".equals(ttsVoiceStatus) ? newLocale.getDisplayName() + ": LANG_COUNTRY_VAR_AVAILABLE" : ttsVoiceStatus;
                            ttsVoiceUsed = getVoiceUsed();
                            break;
                        case TextToSpeech.LANG_NOT_SUPPORTED:
                            // maybe weird, but I didn't want to introduce parameter in around 5 methods just to do this if condition
                            if (isSettingsActivity(act)) {
                                AlertDialog.Builder builder = createAlertDialog(R.string.tts_language_not_supported_title, R.string.tts_language_not_supported, new IntentStarter(act, Intent.ACTION_VIEW, Uri.parse("market://search?q=text to speech engine")), act);
                                builder.show();
                            }
                            ttsVoiceStatus = newLocale.getDisplayName() + ": LANG_NOT_SUPPORTED";
                            ttsVoiceUsed = getVoiceUsed();
                            break;
                    }
                }
            }

            private boolean isSettingsActivity(final Context ctx) {
                return ctx instanceof SettingsActivity;
            }

            private String getVoiceUsed() {
                try {
                    if (android.os.Build.VERSION.SDK_INT >= 21) {
                        if (mTts.getVoice() != null) {
                            return mTts.getVoice().toString() + " (API " + android.os.Build.VERSION.SDK_INT + ")";
                        }
                    } else {
                        return mTts.getLanguage() + " (API " + android.os.Build.VERSION.SDK_INT + " only reports language)";
                    }
                } catch (RuntimeException e) {
                // mTts.getVoice() might throw NPE
                }
                return "-";
            }
        });
        mTts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {

            // The call back is on a binder thread.
            @Override
            public synchronized void onUtteranceCompleted(String utteranceId) {
                if (--ttsRequests <= 0)
                    abandonAudioFocus();
                log.debug("ttsRequests=" + ttsRequests);
                if (ttsRequests < 0) {
                    ttsRequests = 0;
                }
            }
        });
    }
}
Also used : Locale(java.util.Locale) OnInitListener(android.speech.tts.TextToSpeech.OnInitListener) Context(android.content.Context) TextToSpeech(android.speech.tts.TextToSpeech) OnUtteranceCompletedListener(android.speech.tts.TextToSpeech.OnUtteranceCompletedListener) SettingsActivity(net.osmand.plus.activities.SettingsActivity)

Aggregations

OnInitListener (android.speech.tts.TextToSpeech.OnInitListener)2 SuppressLint (android.annotation.SuppressLint)1 Activity (android.app.Activity)1 AlertDialog (android.app.AlertDialog)1 Dialog (android.app.Dialog)1 ProgressDialog (android.app.ProgressDialog)1 ComponentName (android.content.ComponentName)1 Context (android.content.Context)1 DialogInterface (android.content.DialogInterface)1 OnDismissListener (android.content.DialogInterface.OnDismissListener)1 Intent (android.content.Intent)1 AudioManager (android.media.AudioManager)1 TextToSpeech (android.speech.tts.TextToSpeech)1 EngineInfo (android.speech.tts.TextToSpeech.EngineInfo)1 OnUtteranceCompletedListener (android.speech.tts.TextToSpeech.OnUtteranceCompletedListener)1 FragmentActivity (android.support.v4.app.FragmentActivity)1 RecyclerView (android.support.v7.widget.RecyclerView)1 LayoutInflater (android.view.LayoutInflater)1 MenuItem (android.view.MenuItem)1 OnMenuItemClickListener (android.view.MenuItem.OnMenuItemClickListener)1