Search in sources :

Example 1 with OnUtteranceCompletedListener

use of android.speech.tts.TextToSpeech.OnUtteranceCompletedListener 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)

Example 2 with OnUtteranceCompletedListener

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

the class TTSEngine method speakToFile.

public void speakToFile(final DocumentController controller, final int page, final String folder, final ResultResponse<String> info) {
    LOG.d("speakToFile", page, controller.getPageCount());
    if (page >= controller.getPageCount() || !TempHolder.isRecordTTS) {
        LOG.d("speakToFile finish", page, controller.getPageCount());
        info.onResultRecive((controller.getActivity().getString(R.string.success)));
        return;
    }
    info.onResultRecive((page + 1) + " / " + controller.getPageCount());
    DecimalFormat df = new DecimalFormat("0000");
    String pageName = "page-" + df.format(page + 1);
    final String wav = new File(folder, pageName + WAV).getPath();
    String fileText = controller.getTextForPage(page);
    ttsEngine.synthesizeToFile(fileText, map, wav);
    TTSEngine.get().getTTS().setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {

        @Override
        public void onUtteranceCompleted(String utteranceId) {
            LOG.d("speakToFile onUtteranceCompleted", page, controller.getPageCount());
            speakToFile(controller, page + 1, folder, info);
        }
    });
}
Also used : OnUtteranceCompletedListener(android.speech.tts.TextToSpeech.OnUtteranceCompletedListener) DecimalFormat(java.text.DecimalFormat) File(java.io.File)

Example 3 with OnUtteranceCompletedListener

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

the class TTSService method playPage.

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
private void playPage(String preText, int pageNumber, String anchor) {
    if (pageNumber != -1) {
        EventBus.getDefault().post(new MessagePageNumber(pageNumber));
        AppState.get().lastBookPage = pageNumber;
        CodecDocument dc = getDC();
        if (dc == null) {
            LOG.d(TAG, "CodecDocument", "is NULL");
            return;
        }
        int pageCount = dc.getPageCount();
        LOG.d(TAG, "CodecDocument PageCount", pageNumber, pageCount);
        if (pageNumber >= pageCount) {
            TempHolder.get().timerFinishTime = 0;
            Vibro.vibrate(1000);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
            TTSEngine.get().getTTS().setOnUtteranceCompletedListener(null);
            TTSEngine.get().speek(LibreraApp.context.getString(R.string.the_book_is_over));
            EventBus.getDefault().post(new TtsStatus());
            return;
        }
        CodecPage page = dc.getPage(pageNumber);
        String pageHTML = page.getPageHTML();
        page.recycle();
        pageHTML = TxtUtils.replaceHTMLforTTS(pageHTML);
        if (TxtUtils.isNotEmpty(anchor)) {
            int indexOf = pageHTML.indexOf(anchor);
            if (indexOf > 0) {
                pageHTML = pageHTML.substring(indexOf);
                LOG.d("find anchor new text", pageHTML);
            }
        }
        LOG.d(TAG, pageHTML);
        if (TxtUtils.isEmpty(pageHTML)) {
            LOG.d("empty page play next one", emptyPageCount);
            emptyPageCount++;
            if (emptyPageCount < 3) {
                playPage("", AppState.get().lastBookPage + 1, null);
            }
            return;
        }
        emptyPageCount = 0;
        String[] parts = TxtUtils.getParts(pageHTML);
        String firstPart = parts[0];
        final String secondPart = parts[1];
        if (TxtUtils.isNotEmpty(preText)) {
            preText = TxtUtils.replaceLast(preText, "-", "");
            firstPart = preText + firstPart;
        }
        if (Build.VERSION.SDK_INT >= 15) {
            TTSEngine.get().getTTS().setOnUtteranceProgressListener(new UtteranceProgressListener() {

                @Override
                public void onStart(String utteranceId) {
                }

                @Override
                public void onError(String utteranceId) {
                    TTSEngine.get().stop();
                }

                @Override
                public void onDone(String utteranceId) {
                    LOG.d(TAG, "onUtteranceCompleted");
                    if (TempHolder.get().timerFinishTime != 0 && System.currentTimeMillis() > TempHolder.get().timerFinishTime) {
                        LOG.d(TAG, "Timer");
                        TempHolder.get().timerFinishTime = 0;
                        return;
                    }
                    playPage(secondPart, AppState.get().lastBookPage + 1, null);
                    SettingsManager.updateTempPage(AppState.get().lastBookPath, AppState.get().lastBookPage + 1);
                }
            });
        } else {
            TTSEngine.get().getTTS().setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {

                @Override
                public void onUtteranceCompleted(String utteranceId) {
                    LOG.d(TAG, "onUtteranceCompleted");
                    if (TempHolder.get().timerFinishTime != 0 && System.currentTimeMillis() > TempHolder.get().timerFinishTime) {
                        LOG.d(TAG, "Timer");
                        TempHolder.get().timerFinishTime = 0;
                        return;
                    }
                    playPage(secondPart, AppState.get().lastBookPage + 1, null);
                    SettingsManager.updateTempPage(AppState.get().lastBookPath, AppState.get().lastBookPage + 1);
                }
            });
        }
        TTSNotification.show(AppState.get().lastBookPath, pageNumber + 1);
        TTSEngine.get().speek(firstPart);
        EventBus.getDefault().post(new TtsStatus());
        savePage();
    }
}
Also used : OnUtteranceCompletedListener(android.speech.tts.TextToSpeech.OnUtteranceCompletedListener) UtteranceProgressListener(android.speech.tts.UtteranceProgressListener) CodecPage(org.ebookdroid.core.codec.CodecPage) CodecDocument(org.ebookdroid.core.codec.CodecDocument) TargetApi(android.annotation.TargetApi)

Aggregations

OnUtteranceCompletedListener (android.speech.tts.TextToSpeech.OnUtteranceCompletedListener)3 TargetApi (android.annotation.TargetApi)1 Context (android.content.Context)1 TextToSpeech (android.speech.tts.TextToSpeech)1 OnInitListener (android.speech.tts.TextToSpeech.OnInitListener)1 UtteranceProgressListener (android.speech.tts.UtteranceProgressListener)1 File (java.io.File)1 DecimalFormat (java.text.DecimalFormat)1 Locale (java.util.Locale)1 SettingsActivity (net.osmand.plus.activities.SettingsActivity)1 CodecDocument (org.ebookdroid.core.codec.CodecDocument)1 CodecPage (org.ebookdroid.core.codec.CodecPage)1