Example usage for android.speech.tts TextToSpeech TextToSpeech

List of usage examples for android.speech.tts TextToSpeech TextToSpeech

Introduction

In this page you can find the example usage for android.speech.tts TextToSpeech TextToSpeech.

Prototype

public TextToSpeech(Context context, OnInitListener listener) 

Source Link

Document

The constructor for the TextToSpeech class, using the default TTS engine.

Usage

From source file:com.mobilevangelist.glass.helloworld.GetTheWeatherActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ArrayList<String> voiceResults = getIntent().getExtras().getStringArrayList(RecognizerIntent.EXTRA_RESULTS);
    if (voiceResults != null && voiceResults.size() > 0) {
        spokenText = voiceResults.get(0);
    }/*from  w ww .java  2  s.  co  m*/

    Log.i("TEST: ", spokenText);

    _speech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            //          _speech.speak("The weather is" + mCurrent + "Fahrenheit and" + mDescription, TextToSpeech.QUEUE_FLUSH, null);
        }
    });

    setContentView(R.layout.layout_get_the_weather);
    _weatherIconImageView = (ImageView) findViewById(R.id.weatherIconImageView);
    _mainTextView = (TextView) findViewById(R.id.main_text_view);
    new FetchWeather().execute();
}

From source file:org.easyaccess.phonedialer.CallStateService.java

@Override
public void onCreate() {

    telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    callStateListener = new CallStateListener();
    callState = telephonyManager.getCallState();
    telephonyManager.listen(callStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    callState = telephonyManager.getCallState();
    broadcaster = LocalBroadcastManager.getInstance(this);

    tts = new TextToSpeech(this, this);

    this.bReceiver = new BroadcastReceiver() {
        @Override//www.ja  v  a  2 s . c o m
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Utils.INCOMING_CALL)) {

                /**
                 * Extentia : 
                 * As per the security guidelines third party apps can't receive/answer call programmatically 
                 * unless its a system app. So user must need to use default app to receive/answer call. 
                 * Hiding below piece of code to display default app to answer call.
                 * * */
                //               cxt = context;
                //               String number = intent.getStringExtra("message");
                //               callingDetails = new ContactManager(getBaseContext())
                //                     .getNameFromNumber(number);
                //               // play ringtone
                //               // get custom ringtone
                //               playRingtone(number);
                //               // announce number
                //               // Display Calling Activity in order to receive key events
                //               Utils.callingDetails = callingDetails;
                //               myIntent = new Intent(getBaseContext(), CallingScreen.class);
                //               myIntent.putExtra("type", Utils.INCOMING);
                //               myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //               
                //               new Handler().postDelayed(new Runnable() {
                //                  @Override
                //                  public void run() {
                //                     startActivity(myIntent);
                //                  }
                //               }, 2000);

            } else if (Intent.ACTION_NEW_OUTGOING_CALL.equals(intent.getAction())) {
                // new outgoing call
                final String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
                callingDetails = new ContactManager(getBaseContext()).getNameFromNumber(number);
                Utils.callingDetails = callingDetails;
            }
        }
    };

    LocalBroadcastManager.getInstance(this).registerReceiver((this.bReceiver),
            new IntentFilter(Utils.INCOMING_CALL));
    LocalBroadcastManager.getInstance(this).registerReceiver((this.bReceiver),
            new IntentFilter("android.intent.action.PHONE_STATE"));
    if (Accelerometer.isSupported(this)) {
        // Start Accelerometer Listening
        Accelerometer.startListening(this);
    }

    MediaButton_Receiver mediaReceiver = new MediaButton_Receiver();
    IntentFilter filterVolume = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
    registerReceiver(mediaReceiver, filterVolume);

    SettingsContentObserver mSettingsContentObserver = new SettingsContentObserver(this, new Handler());
    getApplicationContext().getContentResolver().registerContentObserver(
            android.provider.Settings.System.CONTENT_URI, true, mSettingsContentObserver);
}

From source file:com.example.h156252.connected_cars.CarGrid.java

/** Called when the activity is first created. */
@Override//from  w  w  w  .j  av a2  s  .c  o m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_car_grid);
    try {
        Window window = getWindow();

        // clear FLAG_TRANSLUCENT_STATUS flag:
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        // add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

        // finally change the color
        window.setStatusBarColor(Color.rgb(0, 0, 0));
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.rgb(0, 0, 0)));
    } catch (Exception e) {
        // Toast.makeText(getApplicationContext(),"Exception in actionbar  "+e.getLocalizedMessage(),Toast.LENGTH_SHORT).show();
    }
    session = new SessionManagement(this);
    tts = new TextToSpeech(this, this);
    //Toast.makeText(getApplicationContext(),"Entering activity",Toast.LENGTH_SHORT).show();
    Intent intent = getIntent();
    String result = intent.getStringExtra(HomeScreen.EXTRA_MESSAGE);
    //Toast.makeText(getApplicationContext(),"obtaining result: " +result,Toast.LENGTH_SHORT).show();
    ArrayList<String> listdata = new ArrayList<String>();

    try {

        JSONArray jArray = new JSONArray(result);
        if (jArray != null) {
            for (int i = 0; i < jArray.length(); i++) {

                String jstr = jArray.get(i).toString();
                JSONObject jObj = new JSONObject(jstr);
                String id = jObj.getString("id");
                //String phone = jObj.getString("phone");
                String brand = jObj.getString("text");
                String text = jObj.getString("cartext");
                String carno = jObj.getString("carnum");
                String color = jObj.getString("color");
                //String isDone = jObj.getString("isDone");
                String result_combine = "CAR " + i + ":\nCar id : #" + id + "*\n" + "License No.   : " + carno
                        + "\n" + "Color   : " + color + "\n" + "Brand   : " + brand + "\n"
                        + "Text behind car   : " + text;
                String rr = "Success " + result_combine;
                //Toast.makeText(getApplicationContext(),rr,Toast.LENGTH_SHORT).show();
                String own_id = session.getID();
                if (!(id.equals(own_id)))
                    listdata.add(result_combine);
            }
        }
    } catch (Exception e) {
        //Toast.makeText(getApplicationContext(),e.getLocalizedMessage(),Toast.LENGTH_SHORT).show();
    }

    //Toast.makeText(getApplicationContext(),"out of json",Toast.LENGTH_SHORT).show();
    final GridView gridview = (GridView) findViewById(R.id.gridview);
    // final String[] items = new String[] { "Item1", "Item2", "Item3","Item4", "Item5", "Item6", "Item7", "Item8" };

    ArrayAdapter<String> ad = new ArrayAdapter<String>(getApplicationContext(),
            android.R.layout.simple_list_item_1, listdata);
    //Toast.makeText(getApplicationContext(),"setting array adapter",Toast.LENGTH_SHORT).show();
    //gridview.setBackgroundColor(Color.GRAY);

    gridview.setNumColumns(2);
    gridview.setGravity(Gravity.CENTER);
    gridview.setAdapter(ad);
    gridview.setBackgroundColor(Color.GRAY);
    //Toast.makeText(getApplicationContext(),"setting grid view",Toast.LENGTH_SHORT).show();
    gridview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
            // TODO Auto-generated method stub
            // Toast.makeText(getApplicationContext(), "" + arg2,Toast.LENGTH_SHORT).show();
            //Toast.makeText(getApplicationContext(),"Prompting speech",Toast.LENGTH_SHORT).show();

            try {
                String s = ((TextView) v).getText().toString();

                int start = 0; // '(' position in string
                int end = 0; // ')' position in string
                for (int i = 0; i < s.length(); i++) {
                    if (s.charAt(i) == '#') // Looking for '(' position in string
                        start = i;
                    else if (s.charAt(i) == '*') // Looking for ')' position in  string
                        end = i;
                }
                receiver_id = s.substring(start + 1, end);

                //Toast.makeText(getApplicationContext(), "ID: " + receiver_id, Toast.LENGTH_SHORT).show();
                //promptSpeechInput();

            } catch (Exception e) {
                // Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }

            //receiver_id = grid_text.substring(grid_text.indexOf("#") + 1, grid_text.indexOf("#"));
            //Toast.makeText(getApplicationContext(),receiver_id,Toast.LENGTH_SHORT).show();

            try {
                promptSpeechInput();
            } catch (Exception e) {
                //Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }

            try {
                Intent intent_rate = new Intent(getApplicationContext(), RateDriving.class);
                intent_rate.putExtra(EXTRA_MESSAGE, receiver_id);
                startActivity(intent_rate);

            } catch (Exception e) {
                //Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }

            //new VoiceTask().execute("http://myfirst.au-syd.mybluemix.net/api/Items");
        }
    });

}

From source file:com.ola.insta.BookingAcivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(getLayoutId());/* w  ww  .ja  v  a 2 s.  c o m*/
    mTextToSpeech = new TextToSpeech(this, this);

    mUtility = new Utilities();
    mProgressDialog = mUtility.GetProcessDialog(this);
    context = BookingAcivity.this;

    Intent intent = getIntent();
    mCabId = intent.getStringExtra(Constants.CAB_ID);
    mCabLat = intent.getDoubleExtra(Constants.CAB_LAT, 0.0);
    mCabLng = intent.getDoubleExtra(Constants.CAB_LANG, 0.0);
    mCabEta = intent.getLongExtra(Constants.CAB_ETA, 0);
    init();
}

From source file:com.abid_mujtaba.fetchheaders.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);//from   ww w  . j a v  a2  s. c o m

    if (savedInstanceState != null) // If the passed in state information bundle is non-empty we expect it to contain the saved value of fShowSeen. We also pass in a default value.
    {
        fShowSeen = savedInstanceState.getBoolean(BUNDLE_FLAG_SHOW_SEEN, false);
    }

    scrollList = (LinearLayout) findViewById(R.id.scrollList);

    if (mTTS == null) // If onCreate is called multiple times we do NOT want to create multiple TextToSpeech objects
    {
        mTTS = new TextToSpeech(this, this);
    }

    if (Account.numberOfAccounts() > 0) // Accounts have been specified
    {
        TextView tvEmpty = (TextView) findViewById(R.id.txtNoAccounts); // We start by removing the No Accounts view since accounts are present
        scrollList.removeView(tvEmpty);

        FragmentManager fM = getSupportFragmentManager();
        FragmentTransaction fT = fM.beginTransaction();

        for (int ii = 0; ii < Account.numberOfAccounts(); ii++) {
            String tag = "TAG_" + ii; // This is the tag we will use to get a handle on the fragment in the FragmentManager

            AccountFragment aF = (AccountFragment) fM.findFragmentByTag(tag); // We attempt to access the fragment via the specified tag

            if (aF == null) // This indicates that the Fragment does not exist yet so we create it. It has setRetainInstance(true) so it persists across configuration changes.
            {
                aF = AccountFragment.newInstance(ii);

                fT.add(R.id.scrollList, aF, tag); // Note: The addition to the scrollList only happens when aF == null, which happens when the persistent fragment has not been created yet
            } //       Since Views retain state across config changes the scrollList remembers that it has fragments added to it

            mFragments.add(aF);
        }

        fT.commit();
    }
}

From source file:com.guanqing.hao.OcrCaptureActivity.java

private void init() {
    mDimView = findViewById(R.id.dim_view);
    final CameraSourcePreview preview = (CameraSourcePreview) findViewById(R.id.preview);
    mGraphicOverlay = (GraphicOverlay<OcrGraphic>) findViewById(R.id.graphicOverlay);
    mDict = new Dict(this);

    mCameraSourceHelper = new CameraSourceHelper(this, preview, mGraphicOverlay, mDict);

    gestureDetector = new GestureDetector(this, new CaptureGestureListener());
    scaleGestureDetector = new ScaleGestureDetector(this, mCameraSourceHelper);

    // Set up the Text To Speech engine.
    TextToSpeech.OnInitListener listener = new TextToSpeech.OnInitListener() {
        @Override//w  ww. j  a  v a  2s.  c  o m
        public void onInit(final int status) {
            if (status == TextToSpeech.SUCCESS) {
                tts.setLanguage(Locale.US);
            }
        }
    };
    tts = new TextToSpeech(this.getApplicationContext(), listener);
}

From source file:com.xengar.android.englishverbs.ui.UniversalFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    if (getArguments() != null) {
        verbsType = getArguments().getString(VERB_TYPE, BOTH);
        itemType = getArguments().getString(ITEM_TYPE, LIST);
        sortTYpe = getArguments().getString(SORT_TYPE, ALPHABET);
    }/*from  w w w.  java 2s.c  o  m*/

    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_universal, container, false);

    mCustomErrorView = (CustomErrorView) view.findViewById(R.id.error);
    mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler);
    progressBar = (CircularProgressBar) view.findViewById(R.id.progressBar);
    mVerbs = new ArrayList<>();

    // initialize Speaker
    tts = new TextToSpeech(getContext(), new TextToSpeech.OnInitListener() {
        @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) {
                    if (LOG) {
                        Log.e("TTS", "This Language is not supported");
                    }
                }
            } else {
                if (LOG) {
                    Log.e("TTS", "Initilization Failed!");
                }
            }
        }
    });
    mAdapter = new VerbAdapter(mVerbs, itemType, tts);

    return view;
}

From source file:ai.api.lejossample.MainActivity.java

private void initTTS() {
    ttsEngine = new TextToSpeech(this, new OnInitListener() {
        @Override//from   w  w  w. j ava2s  . c  o m
        public void onInit(int initStatus) {
            if (initStatus == TextToSpeech.SUCCESS) {
                ttsEngine.setLanguage(Locale.US);
                ttsReady = true;
            } else {
                Log.d(TAG, "Can't initialize TextToSpeech");
            }

        }
    });
}

From source file:com.theultimatelabs.scale.ScaleActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.scale);//from   ww w.  j av a2  s.  c  o  m

    Log.v(TAG, "onCreate");

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    mSettings = getSharedPreferences(PREFS, 0);

    mUnitsText = mSettings.getString("unitsText", "grams");
    mUnitsRatio = mSettings.getFloat("unitsRatio", (float) 1.0);

    mTts = new TextToSpeech(this, this);

    mUnitsView = (TextView) findViewById(R.id.text_unit);
    mUnitsView.setText(mUnitsText);

    findViewById(R.id.text_unit).setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            while (mTts.isSpeaking())
                ;
            Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
            intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say Units");
            startActivityForResult(intent, 0);

            if (adView != null) {
                adView.loadAd(new AdRequest());
            }

        }
    });

    mWeightTextView = (TextView) findViewById(R.id.text_weight);
    mWeightTextView.setText("00.00");
    /*
     * TextPaint weightTextPaint = mWeightTextView.getPaint(); CharSequence
     * weightText = mWeightTextView.getText(); while (weightText !=
     * TextUtils.ellipsize(weightText, weightTextPaint,
     * getWindowManager().getDefaultDisplay
     * ().getWidth()*2/3,TextUtils.TruncateAt.END)) {
     * weightTextPaint.setTextSize(weightTextPaint.getTextSize() - 1); }
     */

    mWeightTextView.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Zero'd", Toast.LENGTH_LONG).show();
            mZeroGrams = mWeightGrams;
            if (adView != null) {
                adView.loadAd(new AdRequest());
            }
        }
    });
    mWeightTextView.setOnLongClickListener(new OnLongClickListener() {
        public boolean onLongClick(View v) {
            mZeroGrams = 0;
            Toast.makeText(getApplicationContext(), "Reset", Toast.LENGTH_LONG).show();
            if (adView != null) {
                adView.loadAd(new AdRequest());
            }
            return true;
        }
    });

    disableAdsText = (TextView) findViewById((R.id.text_disableAds));
    disableAdsText.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            new AlertDialog.Builder(ScaleActivity.this).setTitle("Keep Software Free and Open Source")
                    .setMessage("Ads help support further development, but they are OPTIONAL."
                            + " If you choose to disable ads, please consider donating. All dontations"
                            + " go towards purchasing hardware for open source development. "
                            + "Disabling ads or donating will not change the features availble in this app."
                            + " Thank you. rob@theultimatelabs.com")
                    .setPositiveButton("Disable Ads", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            adLayout.removeAllViews();
                            adView.removeAllViews();
                            disableAdsText.setVisibility(View.INVISIBLE);
                            mSettings.edit().putBoolean("ads", false).commit();
                            adView = null;
                        }
                    }).setCancelable(true).setNegativeButton("Keep Ads", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }).setNeutralButton("Disable Ads + Donate", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            adLayout.removeAllViews();
                            adView.removeAllViews();
                            disableAdsText.setVisibility(View.INVISIBLE);
                            mSettings.edit().putBoolean("ads", false).commit();
                            adView = null;
                            startActivity(new Intent(Intent.ACTION_VIEW,
                                    Uri.parse("http://blog.theultimatelabs.com/p/donate.html")));
                        }
                    }).show();
        }
    });

    TextView aboutText = (TextView) findViewById((R.id.text_about));
    aboutText.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            startActivity(new Intent(getApplicationContext(), AboutActivity.class));
        }
    });

    /*
     * .setMessage() new AlertDialog.Builder(this) .setMessage(mymessage)
     * .setTitle(title) .setCancelable(true)
     * .setNeutralButton(android.R.string.cancel, new
     * DialogInterface.OnClickListener() { public void
     * onClick(DialogInterface dialog, int whichButton){} }) .show(); }}
     */
    // /

    mDensitiesJson = loadJsonResource(R.raw.densities);
    mVolumesJson = loadJsonResource(R.raw.volumes);
    mWeightsJson = loadJsonResource(R.raw.weights);

    // Initiate a generic request to load it with an ad
    if (mSettings.getBoolean("ads", true)) {
        // Create the adViewj
        adView = new AdView(this, AdSize.SMART_BANNER, "a15089dfb39c5a8");

        // Log.w(TAG, new Integer(R.id.layout_ads).toString());
        adLayout = (LinearLayout) findViewById(R.id.layout_ads);

        // Add the adView to it
        adLayout.addView(adView, 0);
        disableAdsText.setVisibility(View.VISIBLE);
    } else {
        disableAdsText.setVisibility(View.INVISIBLE);
        adView = null;
    }

    Intent intent = getIntent();
    mDevice = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

    findScale();

}

From source file:com.remedy.glass.RemedyService.java

@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/*from  w w  w.  j a  v  a 2s  . co m*/
        public void onInit(int status) {
            // Do nothing.
        }
    });

    LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(mLogoutMessageReceiver,
            new IntentFilter("logout"));
}