Search in sources :

Example 96 with TextToSpeech

use of android.speech.tts.TextToSpeech in project chefly_android by chef-ly.

the class GetCookingActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_get_cooking);
    speechListener = new ttsUtteranceListener();
    DisplayMetrics metrics = getResources().getDisplayMetrics();
    width = metrics.widthPixels;
    height = metrics.heightPixels;
    // View Pager
    pager = (ViewPager) findViewById(R.id.viewpager);
    // Gesture Detector to repeat the current step when it detects a single tap on the screen
    final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            if (hasDirections) {
                if (step < directions.size()) {
                    read(directions.get(step));
                } else {
                    read(getResources().getString(R.string.bonAppetit));
                }
            }
            return super.onSingleTapConfirmed(e);
        }

        @Override
        public void onLongPress(MotionEvent e) {
            super.onLongPress(e);
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            return super.onDoubleTap(e);
        }
    });
    // set on touch listener to ViewPager
    pager.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return gestureDetector.onTouchEvent(event);
        }
    });
    pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            step = position;
            updateStepText();
            read(directions.get(position));
        }

        @Override
        public void onPageSelected(int position) {
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    });
    // Text view to display the current step number
    stepText = (TextView) findViewById(R.id.step);
    // Exit Button
    Button exit;
    exit = (Button) findViewById(R.id.exit);
    exit.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            setResult(RESULT_OK);
            finish();
        }
    });
    ImageButton btnSpeak;
    btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
    btnSpeak.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
        }
    });
    textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {

        @Override
        public void onInit(int status) {
            if (status != TextToSpeech.ERROR) {
                textToSpeech.setLanguage(Locale.US);
                // Log.d(TAG, "Quality -> " + textToSpeech.getVoice().getQuality());
                if (directions.size() > 0) {
                    read(directions.get(0));
                }
            }
        }
    });
    // TODO replace with speech recognizer
    Button ingredBtn = (Button) findViewById(R.id.ingredientsBtn);
    ingredBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            FragmentManager fm = getSupportFragmentManager();
            ingredientsPopup.show(fm, "Ingredients");
            getSupportFragmentManager().executePendingTransactions();
            if (ingredientsPopup.getDialog().getWindow() != null)
                ingredientsPopup.getDialog().getWindow().setLayout((6 * width) / 7, (4 * height) / 5);
        }
    });
    // TODO replace with speech recognizer
    Button direcBtn = (Button) findViewById(R.id.directionsBtn);
    direcBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            FragmentManager fm = getSupportFragmentManager();
            if (directionsPopup != null) {
                directionsPopup.show(fm, "Directions");
                getSupportFragmentManager().executePendingTransactions();
                if (directionsPopup.getDialog().getWindow() != null)
                    directionsPopup.getDialog().getWindow().setLayout((6 * width) / 7, (4 * height) / 5);
            } else {
                Log.d(TAG, "Directions pop up is null.  Directions size = " + directions.size());
            }
        }
    });
    int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.RECORD_AUDIO }, PERMISSIONS_REQUEST_RECORD_AUDIO);
    // return;
    } else {
        voiceRec.runRec();
    }
}
Also used : GestureDetector(android.view.GestureDetector) TextToSpeech(android.speech.tts.TextToSpeech) DisplayMetrics(android.util.DisplayMetrics) ImageView(android.widget.ImageView) View(android.view.View) TextView(android.widget.TextView) ViewPager(android.support.v4.view.ViewPager) MotionEvent(android.view.MotionEvent) FragmentManager(android.support.v4.app.FragmentManager) ImageButton(android.widget.ImageButton) ImageButton(android.widget.ImageButton) Button(android.widget.Button)

Example 97 with TextToSpeech

use of android.speech.tts.TextToSpeech in project gdk-compass-sample by googleglass.

the class CompassService method onCreate.

@Override
public void onCreate() {
    super.onCreate();
    // Even though the text-to-speech engine is only used in response to a menu action, we
    // initialize it when the application starts so that we avoid delays that could occur
    // if we waited until it was needed to start it up.
    mSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {

        @Override
        public void onInit(int status) {
        // Do nothing.
        }
    });
    SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    mOrientationManager = new OrientationManager(sensorManager, locationManager);
    mLandmarks = new Landmarks(this);
}
Also used : LocationManager(android.location.LocationManager) SensorManager(android.hardware.SensorManager) Landmarks(com.google.android.glass.sample.compass.model.Landmarks) TextToSpeech(android.speech.tts.TextToSpeech)

Example 98 with TextToSpeech

use of android.speech.tts.TextToSpeech in project Utterance by benbahrenburg.

the class SpeechProxy method onInit.

@Override
public void onInit(int status) {
    try {
        if (_tts == null) {
            _tts = new TextToSpeech(TiApplication.getInstance().getApplicationContext(), this);
        }
        if (status == TextToSpeech.LANG_MISSING_DATA || status == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.e(_logName, "This Language is not supported");
            if (hasListeners("completed")) {
                HashMap<String, Object> event = new HashMap<String, Object>();
                event.put("success", false);
                event.put("message", "This Language is not supported");
                event.put("text", _text);
                event.put("voice", _voice);
                fireEvent("completed", event);
            }
        }
        if (status == TextToSpeech.SUCCESS) {
            // Log.d(_logName, "Adding OnUtteranceCompletedListener");
            _tts.setOnUtteranceCompletedListener(this);
            _voice = _tts.getLanguage().toString();
        }
    } catch (Exception error) {
        if (hasListeners("completed")) {
            HashMap<String, Object> event = new HashMap<String, Object>();
            event.put("success", false);
            event.put("message", "General Err: " + error.getMessage());
            event.put("text", _text);
            event.put("voice", _voice);
            fireEvent("completed", event);
        }
        Log.e(UtteranceModule.MODULE_FULL_NAME, error.getMessage());
        error.printStackTrace();
    }
}
Also used : HashMap(java.util.HashMap) TextToSpeech(android.speech.tts.TextToSpeech)

Example 99 with TextToSpeech

use of android.speech.tts.TextToSpeech in project android_packages_apps_Settings by omnirom.

the class TextToSpeechSettings method onResume.

@Override
public void onResume() {
    super.onResume();
    // We tend to change the summary contents of our widgets, which at higher text sizes causes
    // them to resize, which results in the recyclerview smoothly animating them at inopportune
    // times. Disable the animation so widgets snap to their positions rather than sliding
    // around while the user is interacting with it.
    getListView().getItemAnimator().setMoveDuration(0);
    if (mTts == null || mCurrentDefaultLocale == null) {
        return;
    }
    if (!mTts.getDefaultEngine().equals(mTts.getCurrentEngine())) {
        final TextToSpeechViewModel ttsViewModel = ViewModelProviders.of(this).get(TextToSpeechViewModel.class);
        try {
            // If the current engine isn't the default engine shut down the current engine in
            // preparation for creating the new engine.
            ttsViewModel.shutdownTts();
        } catch (Exception e) {
            Log.e(TAG, "Error shutting down TTS engine" + e);
        }
        final Pair<TextToSpeech, Boolean> ttsAndNew = ttsViewModel.getTtsAndWhetherNew(mInitListener);
        mTts = ttsAndNew.first;
        if (!ttsAndNew.second) {
            successSetup();
        }
        setTtsUtteranceProgressListener();
        initSettings();
    } else {
        // Do set pitch correctly after it may have changed, and unlike speed, it doesn't change
        // immediately.
        final ContentResolver resolver = getContentResolver();
        mTts.setPitch(android.provider.Settings.Secure.getInt(resolver, TTS_DEFAULT_PITCH, TextToSpeech.Engine.DEFAULT_PITCH) / 100.0f);
    }
    Locale ttsDefaultLocale = mTts.getDefaultLanguage();
    if (mCurrentDefaultLocale != null && !mCurrentDefaultLocale.equals(ttsDefaultLocale)) {
        updateWidgetState(false);
        checkDefaultLocale();
    }
}
Also used : Locale(java.util.Locale) TextToSpeech(android.speech.tts.TextToSpeech) MissingResourceException(java.util.MissingResourceException) ActivityNotFoundException(android.content.ActivityNotFoundException) ContentResolver(android.content.ContentResolver)

Example 100 with TextToSpeech

use of android.speech.tts.TextToSpeech in project android_packages_apps_Settings by omnirom.

the class TextToSpeechSettings method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.tts_settings);
    getActivity().setVolumeControlStream(TextToSpeech.Engine.DEFAULT_STREAM);
    mEnginesHelper = new TtsEngines(getActivity().getApplicationContext());
    mLocalePreference = (ListPreference) findPreference(KEY_ENGINE_LOCALE);
    mLocalePreference.setOnPreferenceChangeListener(this);
    mDefaultPitchPref = (SeekBarPreference) findPreference(KEY_DEFAULT_PITCH);
    mDefaultRatePref = (SeekBarPreference) findPreference(KEY_DEFAULT_RATE);
    mActionButtons = ((ActionButtonsPreference) findPreference(KEY_ACTION_BUTTONS)).setButton1Text(R.string.tts_play).setButton1OnClickListener(v -> speakSampleText()).setButton1Enabled(false).setButton2Text(R.string.tts_reset).setButton2OnClickListener(v -> resetTts()).setButton1Enabled(true);
    mUserManager = (UserManager) getActivity().getApplicationContext().getSystemService(Context.USER_SERVICE);
    if (savedInstanceState == null) {
        mLocalePreference.setEnabled(false);
        mLocalePreference.setEntries(new CharSequence[0]);
        mLocalePreference.setEntryValues(new CharSequence[0]);
    } else {
        // Repopulate mLocalePreference with saved state. Will be updated later with
        // up-to-date values when checkTtsData() calls back with results.
        final CharSequence[] entries = savedInstanceState.getCharSequenceArray(STATE_KEY_LOCALE_ENTRIES);
        final CharSequence[] entryValues = savedInstanceState.getCharSequenceArray(STATE_KEY_LOCALE_ENTRY_VALUES);
        final CharSequence value = savedInstanceState.getCharSequence(STATE_KEY_LOCALE_VALUE);
        mLocalePreference.setEntries(entries);
        mLocalePreference.setEntryValues(entryValues);
        mLocalePreference.setValue(value != null ? value.toString() : null);
        mLocalePreference.setEnabled(entries.length > 0);
    }
    final TextToSpeechViewModel ttsViewModel = ViewModelProviders.of(this).get(TextToSpeechViewModel.class);
    Pair<TextToSpeech, Boolean> ttsAndNew = ttsViewModel.getTtsAndWhetherNew(mInitListener);
    mTts = ttsAndNew.first;
    // ensure that we can use the TTS object.
    if (!ttsAndNew.second) {
        successSetup();
    }
    setTtsUtteranceProgressListener();
    initSettings();
}
Also used : SettingsPreferenceFragment(com.android.settings.SettingsPreferenceFragment) Context(android.content.Context) Bundle(android.os.Bundle) AlertDialog(androidx.appcompat.app.AlertDialog) SeekBarPreference(com.android.settings.widget.SeekBarPreference) Pair(android.util.Pair) UtteranceProgressListener(android.speech.tts.UtteranceProgressListener) Intent(android.content.Intent) HashMap(java.util.HashMap) SearchIndexable(com.android.settingslib.search.SearchIndexable) ArrayList(java.util.ArrayList) TtsEngines(android.speech.tts.TtsEngines) ContentResolver(android.content.ContentResolver) EngineInfo(android.speech.tts.TextToSpeech.EngineInfo) Locale(java.util.Locale) TTS_DEFAULT_RATE(android.provider.Settings.Secure.TTS_DEFAULT_RATE) UserHandle(android.os.UserHandle) ViewModelProviders(androidx.lifecycle.ViewModelProviders) Log(android.util.Log) R(com.android.settings.R) BaseSearchIndexProvider(com.android.settings.search.BaseSearchIndexProvider) Collator(java.text.Collator) UserManager(android.os.UserManager) TTS_DEFAULT_PITCH(android.provider.Settings.Secure.TTS_DEFAULT_PITCH) TTS_DEFAULT_SYNTH(android.provider.Settings.Secure.TTS_DEFAULT_SYNTH) MissingResourceException(java.util.MissingResourceException) Set(java.util.Set) SettingsEnums(android.app.settings.SettingsEnums) TextUtils(android.text.TextUtils) GearPreference(com.android.settings.widget.GearPreference) ActionButtonsPreference(com.android.settingslib.widget.ActionButtonsPreference) Secure(android.provider.Settings.Secure) FeatureFactory(com.android.settings.overlay.FeatureFactory) Preference(androidx.preference.Preference) Objects(java.util.Objects) TextToSpeech(android.speech.tts.TextToSpeech) List(java.util.List) SettingsActivity(com.android.settings.SettingsActivity) ActivityNotFoundException(android.content.ActivityNotFoundException) ListPreference(androidx.preference.ListPreference) Utils(com.android.settings.Utils) Collections(java.util.Collections) ActionButtonsPreference(com.android.settingslib.widget.ActionButtonsPreference) TtsEngines(android.speech.tts.TtsEngines) TextToSpeech(android.speech.tts.TextToSpeech)

Aggregations

TextToSpeech (android.speech.tts.TextToSpeech)103 Test (org.junit.Test)34 Locale (java.util.Locale)18 TtsEngines (android.speech.tts.TtsEngines)15 ActivityNotFoundException (android.content.ActivityNotFoundException)12 Intent (android.content.Intent)12 ContentResolver (android.content.ContentResolver)10 MissingResourceException (java.util.MissingResourceException)10 IntentFilter (android.content.IntentFilter)8 TextView (android.widget.TextView)7 Config (org.robolectric.annotation.Config)7 BluetoothAdapter (android.bluetooth.BluetoothAdapter)6 Handler (android.os.Handler)6 UtteranceProgressListener (android.speech.tts.UtteranceProgressListener)6 ArrayAdapter (android.widget.ArrayAdapter)6 Context (android.content.Context)5 HashMap (java.util.HashMap)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 Bundle (android.os.Bundle)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)3