android.speech.tts.TextToSpeech Java Examples

The following examples show how to use android.speech.tts.TextToSpeech. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EventSpeaker.java    From VIA-AI with MIT License 6 votes vote down vote up
public void init(@NonNull Context context, @NonNull OnEventChangeListener listener, boolean enableTTS, boolean enableBeep) {
    mContext = context;
    mOnEventChangeListener = listener;
    b_enableTTS = enableTTS;
    b_enableBeep = enableBeep;

    if(b_enableTTS) {
        Intent checkIntent = new Intent();
        checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        mOnEventChangeListener.postStartActivityForResult(checkIntent, TTS_REQUEST_CODE);
    }

    if(b_enableBeep) {
        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mRingTone = RingtoneManager.getRingtone(context, uri);
    }
}
 
Example #2
Source File: VoiceHelper.java    From AlexaAndroid with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the TextToSpeech instance
 * @return our TextToSpeech instance, if it's initialized
 */
private TextToSpeech getTextToSpeech(){
    int count = 0;

    while(!mIsIntialized){
        if(count < 100)
        {
            count++;
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else{
            throw new IllegalStateException("Text to Speech engine is not initalized");
        }
    }
    return mTextToSpeech;
}
 
Example #3
Source File: TtsService.java    From android-app with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Thread-safety note: executed in a background thread: {@link TtsService#executor}.
 */
private void ttsSpeak(CharSequence text, int queueMode, String utteranceId) {
    if (state != State.PLAYING || !isTtsInitialized) {
        Log.w(TAG, "ttsSpeak() state=" + state + ", isTtsInitialized=" + isTtsInitialized);
        return;
    }

    if (text != null) {
        // TODO: check tts.getMaxSpeechInputLength()?

        Log.v(TAG, "ttsSpeak() speaking " + utteranceId + ": " + text);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            tts.speak(text, queueMode, null, utteranceId);
        } else {
            HashMap<String, String> params = new HashMap<>(2);
            params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utteranceId);
            //noinspection deprecation
            tts.speak(text.toString(), queueMode, params);
        }

        Log.v(TAG, "ttsSpeak() call returned");
    }
}
 
Example #4
Source File: TextToVoice.java    From Primary with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onInit(int status) {
    if (status == TextToSpeech.SUCCESS) {
        int result = mTts.setLanguage(Locale.getDefault());
        isInit = true;

        if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {

            Log.e("error", "This Language is not supported");
        }
        Log.d("TextToSpeech", "Initialization Suceeded! " + System.currentTimeMillis());

        speak(mContext.getString(R.string.voice_ready) + ",");
    } else {
        Log.e("error", "Initialization Failed! " + status);
    }
}
 
Example #5
Source File: VoiceHelper.java    From AlexaAndroid with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a new audio recording based on text passed in, update the callback with the changing states
 * @param text the text to render
 * @param callback
 */
public void getSpeechFromText(String text, SpeechFromTextCallback callback){

    //create a new unique ID
    String utteranceId = AuthorizationManager.createCodeVerifier();

    //add the callback to our list of callbacks
    mCallbacks.put(utteranceId, callback);

    //get our TextToSpeech engine
    TextToSpeech textToSpeech = getTextToSpeech();

    //set up our arguments
    HashMap<String, String> params = new HashMap<>();
    params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utteranceId);

    //request an update from TTS
    textToSpeech.synthesizeToFile(text, params, getCacheFile(utteranceId).toString());
}
 
Example #6
Source File: OcrCaptureActivity.java    From android-vision with Apache License 2.0 6 votes vote down vote up
/**
 * onTap is called to speak the tapped TextBlock, if any, out loud.
 *
 * @param rawX - the raw position of the tap
 * @param rawY - the raw position of the tap.
 * @return true if the tap was on a TextBlock
 */
private boolean onTap(float rawX, float rawY) {
    OcrGraphic graphic = graphicOverlay.getGraphicAtLocation(rawX, rawY);
    TextBlock text = null;
    if (graphic != null) {
        text = graphic.getTextBlock();
        if (text != null && text.getValue() != null) {
            Log.d(TAG, "text data is being spoken! " + text.getValue());
            // Speak the string.
            tts.speak(text.getValue(), TextToSpeech.QUEUE_ADD, null, "DEFAULT");
        }
        else {
            Log.d(TAG, "text data is null");
        }
    }
    else {
        Log.d(TAG,"no text detected");
    }
    return text != null;
}
 
Example #7
Source File: MainActivity.java    From Paideia with MIT License 6 votes vote down vote up
@Override
protected void onCreate(final Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

  setContentView(R.layout.activity_camera);

  tts=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
    @Override
    public void onInit(int status) {
        if(status != TextToSpeech.ERROR) {
            tts.setLanguage(Locale.US);
        }
    }
  });
  if (null == savedInstanceState) {
    getFragmentManager()
        .beginTransaction()
        .replace(R.id.container, CameraConnectionFragment.newInstance())
        .commit();
  }
    Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    window.setStatusBarColor(baseColor);
}
 
Example #8
Source File: speechModule.java    From react-native-speech with MIT License 6 votes vote down vote up
/***
 * This method will expose all the available languages in TTS engine
 *
 * @param callback
 */
@ReactMethod
public void getLocale(final Callback callback) {
    new GuardedAsyncTask<Void, Void>(getReactApplicationContext()) {
        @Override
        protected void doInBackgroundGuarded(Void... params) {
            try {
                if (tts == null) {
                    init();
                }
                Locale[] locales = Locale.getAvailableLocales();
                WritableArray data = Arguments.createArray();
                for (Locale locale : locales) {
                    int res = tts.isLanguageAvailable(locale);
                    if (res == TextToSpeech.LANG_COUNTRY_AVAILABLE) {
                        data.pushString(locale.getLanguage());
                    }
                }
                callback.invoke(null, data);
            } catch (Exception e) {
                callback.invoke(e.getMessage());
            }
        }
    }.execute();
}
 
Example #9
Source File: TtsSpeaker.java    From sample-tensorflow-imageclassifier with Apache License 2.0 6 votes vote down vote up
private boolean playJoke(TextToSpeech tts) {
    long now = System.currentTimeMillis();
    // choose a random joke whose last occurrence was far enough in the past
    SortedMap<Long, Utterance> availableJokes = mJokes.headMap(now - JOKE_COOLDOWN_MILLIS);
    Utterance joke = null;
    if (!availableJokes.isEmpty()) {
        int r = RANDOM.nextInt(availableJokes.size());
        int i = 0;
        for (Long key : availableJokes.keySet()) {
            if (i++ == r) {
                joke = availableJokes.remove(key); // also removes from mJokes
                break;
            }
        }
    }
    if (joke != null) {
        joke.speak(tts);
        // add it back with the current time
        mJokes.put(now, joke);
        return true;
    }
    return false;
}
 
Example #10
Source File: AnnouncementPeriodicTask.java    From mytracks with Apache License 2.0 6 votes vote down vote up
/**
 * Called when TTS is ready.
 */
private void onTtsReady() {
  Locale locale = Locale.getDefault();
  int languageAvailability = tts.isLanguageAvailable(locale);
  if (languageAvailability == TextToSpeech.LANG_MISSING_DATA
      || languageAvailability == TextToSpeech.LANG_NOT_SUPPORTED) {
    Log.w(TAG, "Default locale not available, use English.");
    locale = Locale.ENGLISH;
    /*
     * TODO: instead of using english, load the language if missing and show a
     * toast if not supported. Not able to change the resource strings to
     * English.
     */
  }
  tts.setLanguage(locale);

  // Slow down the speed just a bit as it is hard to hear when exercising.
  tts.setSpeechRate(TTS_SPEECH_RATE);

  tts.setOnUtteranceCompletedListener(utteranceListener);
}
 
Example #11
Source File: MainActivity.java    From CT_Android_demos with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	//��ʼ��TTS
	tts = new TextToSpeech(this, this);
	//��ȡ�ؼ�
	speechText = (TextView)findViewById(R.id.speechTextView);  
       speechButton = (Button)findViewById(R.id.speechButton);  
       //Ϊbutton��Ӽ���
       speechButton.setOnClickListener(new OnClickListener(){   
           @Override  
           public void onClick(View v){  
               // TODO Auto-generated method stub  
               tts.speak(speechText.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);  
           }  
       });  
	
}
 
Example #12
Source File: ConversationActivity.java    From TranslateApp with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private void speakOut(String textMessage, String languageCode){
    int result = mTextToSpeech.setLanguage(new Locale(languageCode));
    Log.e("Inside","speakOut "+languageCode+" "+result);
    if (result == TextToSpeech.LANG_MISSING_DATA ){
        Toast.makeText(getApplicationContext(),getString(R.string.language_pack_missing),Toast.LENGTH_SHORT).show();
        Intent installIntent = new Intent();
        installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
        startActivity(installIntent);
    } else if(result == TextToSpeech.LANG_NOT_SUPPORTED) {
        Toast.makeText(getApplicationContext(),getString(R.string.language_not_supported),Toast.LENGTH_SHORT).show();
    } else {
        process_tts.show();
        map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "UniqueID");
        mTextToSpeech.speak(textMessage, TextToSpeech.QUEUE_FLUSH, map);
    }
}
 
Example #13
Source File: TtsHelper.java    From coolreader with MIT License 6 votes vote down vote up
private void speakFromQueue() {
	if (queue != null && queue.size() > currentQueueIndex) {
		SpeakValue val = queue.get(currentQueueIndex);

		HashMap<String, String> params = new HashMap<String, String>();
		params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "ID:" + currentQueueIndex);

		if (val.Val.equals(SILENCE)) {
			tts.playSilence(whiteSpaceDelay, TextToSpeech.QUEUE_FLUSH, params);
		} else {
			tts.speak(val.Val, TextToSpeech.QUEUE_FLUSH, params);
		}

		++currentQueueIndex;
	}
}
 
Example #14
Source File: MainActivity.java    From journaldev with MIT License 6 votes vote down vote up
@Override
public void onInit(int status) {

    if (status == TextToSpeech.SUCCESS) {
        int result = tts.setLanguage(Locale.US);

        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Toast.makeText(getApplicationContext(), "Language not supported", Toast.LENGTH_SHORT).show();
        } else {
            button.setEnabled(true);
        }

    } else {
        Toast.makeText(getApplicationContext(), "Init failed", Toast.LENGTH_SHORT).show();
    }
}
 
Example #15
Source File: CompassService.java    From PTVGlass with MIT License 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    mTimelineManager = TimelineManager.from(this);

    // 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);
}
 
Example #16
Source File: ReceiverSelector.java    From media-button-router with Apache License 2.0 6 votes vote down vote up
/**
 * Moves selection by the amount specified in the list. If we're already at
 * the last item and we're moving forward, wraps to the first item. If we're
 * already at the first item, and we're moving backwards, wraps to the last
 * item.
 * 
 * @param amount
 *            The amount to move, may be positive or negative.
 */
private void moveSelection(int amount) {
    resetTimeout();

    btButtonSelection += amount;

    if (btButtonSelection >= receivers.size()) {
        // wrap
        btButtonSelection = 0;
    } else if (btButtonSelection < 0) {
        // wrap
        btButtonSelection = receivers.size() - 1;
    }

    // May not highlight, but will scroll to item
    getListView().invalidateViews();
    getListView().setSelection(btButtonSelection);

    if (textToSpeech != null) {
        textToSpeech.speak(Utils.getAppName(receivers.get(btButtonSelection), getPackageManager()),
                TextToSpeech.QUEUE_FLUSH, null);
    }

}
 
Example #17
Source File: TtsPlatformImpl.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
/**
 * Attempt to start speaking an utterance. If it returns true, will call back on
 * start and end.
 *
 * @param utteranceId A unique id for this utterance so that callbacks can be tied
 *     to a particular utterance.
 * @param text The text to speak.
 * @param lang The language code for the text (e.g., "en-US").
 * @param rate The speech rate, in the units expected by Android TextToSpeech.
 * @param pitch The speech pitch, in the units expected by Android TextToSpeech.
 * @param volume The speech volume, in the units expected by Android TextToSpeech.
 * @return true on success.
 */
@CalledByNative
private boolean speak(int utteranceId, String text, String lang,
                      float rate, float pitch, float volume) {
    if (!mInitialized) {
        mPendingUtterance = new PendingUtterance(this, utteranceId, text, lang, rate,
                pitch, volume);
        return true;
    }
    if (mPendingUtterance != null) mPendingUtterance = null;

    if (!lang.equals(mCurrentLanguage)) {
        mTextToSpeech.setLanguage(new Locale(lang));
        mCurrentLanguage = lang;
    }

    mTextToSpeech.setSpeechRate(rate);
    mTextToSpeech.setPitch(pitch);

    int result = callSpeak(text, volume, utteranceId);
    return (result == TextToSpeech.SUCCESS);
}
 
Example #18
Source File: EventSpeaker.java    From VIA-AI with MIT License 6 votes vote down vote up
public void pushEvent(SystemEvents event) {
    boolean speak = false;

    if(b_enableTTS && mTTS.isSpeaking()) {
        if(mPrevEvent.getLevel().getIndex() >= event.getLevel().getIndex() && mPrevEvent != event) {
            speak = true;
            mTTS.stop();
        }
    }
    else {
        speak = true;
    }

    if(speak) {
        if(b_enableBeep) {
            if (event.getRingCode() == 1) mRingTone.play();
        }

        if(b_enableTTS) {
            String text = event.getText();
            if (text != null) mTTS.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        }
        mPrevEvent = event;
    }
}
 
Example #19
Source File: AnnouncementPeriodicTaskTest.java    From mytracks with Apache License 2.0 5 votes vote down vote up
public void testStart() {
  doStart();
  OnInitListener ttsInitListener = initListenerCapture.getValue();
  assertNotNull(ttsInitListener);

  AndroidMock.replay(tts);

  ttsInitListener.onInit(TextToSpeech.SUCCESS);

  AndroidMock.verify(mockTask, tts);
}
 
Example #20
Source File: TtsHelper.java    From coolreader with MIT License 5 votes vote down vote up
public TtsHelper(Context context, OnInitListener listener, OnCompleteListener onComplete) {
	tts = new TextToSpeech(context, this);
	this.listener = listener;
	this.onCompleteListener = onComplete;

	queue = new ArrayList<SpeakValue>();
	currentQueueIndex = 0;
}
 
Example #21
Source File: VoiceHelper.java    From AlexaAndroid with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onInit(int status) {
    if(status == TextToSpeech.SUCCESS){
        mIsIntialized = true;
    }else{
        new IllegalStateException("Unable to initialize Text to Speech engine").printStackTrace();
    }
}
 
Example #22
Source File: TTSService.java    From Botifier with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    mTTS = new TextToSpeech(this, this);
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    mSharedPref = PreferenceManager.getDefaultSharedPreferences(this);
}
 
Example #23
Source File: NaviVoice.java    From PocketMaps with MIT License 5 votes vote down vote up
public static void showTtsActivity(Activity activity)
{
  Intent installTTSIntent = new Intent();
  installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
  ArrayList<String> languages = new ArrayList<String>();
  languages.add(DISPLAY_LANG);
  languages.add("en");
  installTTSIntent.putStringArrayListExtra(TextToSpeech.Engine.EXTRA_CHECK_VOICE_DATA_FOR, languages);
  activity.startActivity(installTTSIntent);
}
 
Example #24
Source File: MainPresenterImpl.java    From Speculum-Android with MIT License 5 votes vote down vote up
@SuppressWarnings("deprecation")
public void speak(String sentence) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        String utteranceId = this.hashCode() + "";
        textToSpeech.speak(sentence, TextToSpeech.QUEUE_FLUSH, null, utteranceId);
    } else {
        HashMap<String, String> map = new HashMap<>();
        map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "MessageId");
        textToSpeech.speak(sentence, TextToSpeech.QUEUE_FLUSH, map);
    }
}
 
Example #25
Source File: VoiceActivity.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_voice);
       
       HttpGetImageAction.fetchImage(this, MainActivity.instance.avatar, findViewById(R.id.icon));
	this.tts = new TextToSpeech(this, this);
       
       HttpGetVoiceAction action = new HttpGetVoiceAction(this, (InstanceConfig)MainActivity.instance.credentials());
   	action.execute();
}
 
Example #26
Source File: PreferencesActivity.java    From callerid-for-android with GNU General Public License v3.0 5 votes vote down vote up
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
	if("tts_enabled".equals(key) && sharedPreferences.getBoolean("tts_enabled", true)){
		//make sure the TTS data has been installed
		Intent checkIntent = new Intent();
		checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
		startActivityForResult(checkIntent, CHECK_TTS_DATA);
	}
}
 
Example #27
Source File: TtsSpeaker.java    From sample-tensorflow-imageclassifier with Apache License 2.0 5 votes vote down vote up
@Override
public void speak(TextToSpeech tts) {
    tts.setPitch(0.2f);
    tts.speak("I see dead people...", TextToSpeech.QUEUE_ADD, null, UTTERANCE_ID);
    tts.setPitch(1);
    tts.speak("Just kidding...", TextToSpeech.QUEUE_ADD, null, UTTERANCE_ID);
}
 
Example #28
Source File: MainActivity.java    From reader with MIT License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);

	mTakePhoto = (Button) findViewById(R.id.take_photo);
	mImageView = (ImageView) findViewById(R.id.imageview);
	speak1 = (Button) findViewById(R.id.speak1);
	responseText = (TextView) findViewById(R.id.textView1);

	mTakePhoto.setOnClickListener(this);
	speak1.setOnClickListener(this);
	
	tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
           @Override
           public void onInit(int status) {
               // TODO Auto-generated method stub
               if (status == TextToSpeech.SUCCESS)
               {
                   int result = tts.setLanguage(Locale.CHINA);
                   if (result == TextToSpeech.LANG_MISSING_DATA
                           || result == TextToSpeech.LANG_NOT_SUPPORTED)
                   {
                       Toast.makeText(getApplicationContext(), "Language is not available.",
                               Toast.LENGTH_SHORT).show();
                   }
               } else {
               	Toast.makeText(getApplicationContext(), "Language is available.",
                           Toast.LENGTH_SHORT).show();
               }
           }
       });
}
 
Example #29
Source File: TtsSpeaker.java    From sample-tensorflow-imageclassifier with Apache License 2.0 5 votes vote down vote up
@Override
public void speak(TextToSpeech tts) {
    tts.setPitch(1.5f);
    tts.setSpeechRate(1.5f);
    super.speak(tts);
    tts.setPitch(1f);
    tts.setSpeechRate(1f);
}
 
Example #30
Source File: TtsSpeaker.java    From sample-tensorflow-imageclassifier with Apache License 2.0 5 votes vote down vote up
public void speakResults(TextToSpeech tts, Collection<Recognition> results) {
    if (results.isEmpty()) {
        tts.speak("I don't understand what I see.", TextToSpeech.QUEUE_ADD, null, UTTERANCE_ID);
        if (isFeelingFunnyNow()) {
            tts.speak("Please don't unplug me, I'll do better next time.",
                    TextToSpeech.QUEUE_ADD, null, UTTERANCE_ID);
        }
    } else {
        if (isFeelingFunnyNow()) {
            playJoke(tts);
        }
        Iterator<Recognition> it = results.iterator();

        Recognition first = it.hasNext() ? it.next() : null;
        Recognition second = it.hasNext() ? it.next() : null;
        if (results.size() == 1
                || first.getConfidence() > SINGLE_ANSWER_CONFIDENCE_THRESHOLD) {
            tts.speak(String.format(Locale.getDefault(),
                    "I see a %s", first.getTitle()),
                    TextToSpeech.QUEUE_ADD, null, UTTERANCE_ID);
        } else {
            tts.speak(String.format(Locale.getDefault(), "This is a %s, or maybe a %s",
                    first.getTitle(), second.getTitle()),
                    TextToSpeech.QUEUE_ADD, null, UTTERANCE_ID);
        }
    }

}