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.mobile.lapa.waitandsee.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mRegistrationProgressBar = (ProgressBar) findViewById(R.id.registrationProgressBar);
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override/*from   w  ww . j a v  a2s  . c  o  m*/
        public void onReceive(Context context, Intent intent) {
            mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
            if (!sentToken) {
                mMessageTextView.setText(getString(R.string.token_error_message));
            }
        }
    };

    mMessageTextView = (TextView) findViewById(R.id.messageTextView);
    mTitleTextView = (TextView) findViewById(R.id.titleTextView);
    mUserNameEditText = (EditText) findViewById(R.id.userNameEditText);
    mSubmitButton = (Button) findViewById(R.id.submitButton);

    mUserNameEditText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                mSubmitButton.performClick();
                return true;
            }
            return false;
        }
    });

    if (this.textToSpeech == null) {
        textToSpeech = new TextToSpeech(this.getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status != TextToSpeech.ERROR) {
                    textToSpeech.setLanguage(Locale.ENGLISH); //getDefault());
                }
            }
        });
    }

    Bundle b = getIntent().getExtras();
    String title = "";
    String message = "";
    if (b != null) {
        title = b.getString("TITLE_KEY");
        message = b.getString("MESSAGE_KEY");
    }

    if (title == "" && message == "") { //(b == null) {
        mTitleTextView.setText(getString(R.string.welcome_title));
        mMessageTextView.setText(getString(R.string.welcome_message));
    } else {
        mTitleTextView.setText(title);
        mMessageTextView.setText(message);
        playSound(title);
    }

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }
    // ------- User name ------------
    settings = getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);
    userName = settings.getString("USER_NAME", "");
    if (userName != "") {
        // user name already set
        hideUserFields();
    }
    setUserTitle();
}

From source file:com.vyasware.vaani.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    returnedText = (TextView) findViewById(R.id.textView1);
    outputText = (TextView) findViewById(R.id.textView2);
    progressBar = (ProgressBar) findViewById(R.id.progressBar1);
    toggleButton = (ToggleButton) findViewById(R.id.toggleButton1);

    progressBar.setVisibility(View.INVISIBLE);
    speech = SpeechRecognizer.createSpeechRecognizer(this);
    speech.setRecognitionListener(this);
    recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    //        recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE,
    //                "en");
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName());
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, "hi-IN");
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "hi-IN");
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_ONLY_RETURN_LANGUAGE_PREFERENCE, "hi-IN");
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
    tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
        @Override//from w w  w. j a  v a 2  s .  c  o m
        public void onInit(int status) {
            if (status != TextToSpeech.ERROR) {
                tts.setLanguage(new Locale("hi_IN"));
                tts.setSpeechRate(0.9f);
            }
        }
    });
    returnedText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
            intent.putExtra(SearchManager.QUERY, returnedText.getText());
            if (intent.resolveActivity(getPackageManager()) != null)
                startActivity(intent);

        }
    });

    toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                progressBar.setVisibility(View.VISIBLE);
                progressBar.setIndeterminate(true);
                speech.startListening(recognizerIntent);
                outputText.setText("");
            } else {
                progressBar.setIndeterminate(false);
                progressBar.setVisibility(View.INVISIBLE);
                speech.stopListening();
            }
        }
    });

}

From source file:com.perchtech.humraz.blind.OcrCaptureActivity.java

@Override
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView(R.layout.ocr_capture);
    Speech.getInstance().say("You Are Now In Character Recognition Mode.");
    mPreview = (CameraSourcePreview) findViewById(R.id.preview);
    mGraphicOverlay = (GraphicOverlay<OcrGraphic>) findViewById(R.id.graphicOverlay);

    boolean autoFocus = true;
    boolean useFlash = false;

    int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
    if (rc == PackageManager.PERMISSION_GRANTED) {
        createCameraSource(autoFocus, useFlash);
    } else {//from   w w  w. j a v  a  2s.c o m
        requestCameraPermission();
    }

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

    Snackbar.make(mGraphicOverlay, "Tap to Speak. Pinch/Stretch to zoom", Snackbar.LENGTH_LONG).show();

    TextToSpeech.OnInitListener listener = new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(final int status) {
            if (status == TextToSpeech.SUCCESS) {
                Log.d("OnInitListener", "Text to speech engine started successfully.");
                tts.setLanguage(Locale.US);
            } else {
                Log.d("OnInitListener", "Error starting the text to speech engine.");
            }
        }
    };
    tts = new TextToSpeech(this.getApplicationContext(), listener);
}

From source file:onion.chat.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    db = Database.getInstance(this);
    tor = Tor.getInstance(this);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);//from  w w w  . j av a 2 s  . c o  m
    t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status != TextToSpeech.ERROR) {
                t1.setLanguage(Locale.US);
            }
        }
    });
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            final Dialog[] d = new Dialog[1];

            View v = getLayoutInflater().inflate(R.layout.dialog_connect, null);
            ((TextView) v.findViewById(R.id.id)).setText(Tor.getInstance(MainActivity.this).getID());
            v.findViewById(R.id.qr_show).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    d[0].cancel();
                    showQR();
                }
            });
            v.findViewById(R.id.qr_scan).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    d[0].cancel();
                    scanQR();
                }
            });
            v.findViewById(R.id.enter_id).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    d[0].cancel();
                    addContact();
                }
            });
            v.findViewById(R.id.share_id).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    d[0].cancel();
                    inviteFriend();
                }
            });
            d[0] = new AlertDialog.Builder(MainActivity.this)
                    //.setTitle(R.string.add_contact)
                    .setView(v).show();

        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    startService(new Intent(this, HostService.class));

    findViewById(R.id.myname).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            changeName();
        }
    });

    findViewById(R.id.myaddress).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showQR();
        }
    });

    contactPage = getLayoutInflater().inflate(R.layout.page_contacts, null);
    requestPage = getLayoutInflater().inflate(R.layout.page_requests, null);

    contactRecycler = (RecyclerView) contactPage.findViewById(R.id.contactRecycler);
    requestRecycler = (RecyclerView) requestPage.findViewById(R.id.requestRecycler);

    contactEmpty = contactPage.findViewById(R.id.contactEmpty);
    requestEmpty = requestPage.findViewById(R.id.requestEmpty);

    contactRecycler.setLayoutManager(new LinearLayoutManager(this));
    contactRecycler.setAdapter(new RecyclerView.Adapter<ContactViewHolder>() {
        @Override
        public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            final ContactViewHolder viewHolder = new ContactViewHolder(
                    getLayoutInflater().inflate(R.layout.item_contact, parent, false));
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String toSpeak = viewHolder.name.getText().toString();
                    Toast.makeText(getApplicationContext(), toSpeak, Toast.LENGTH_SHORT).show();
                    t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
                    startActivity(
                            new Intent(Intent.ACTION_VIEW, Uri.parse("chat:" + viewHolder.address.getText()),
                                    getApplicationContext(), ChatActivity.class));
                }
            });
            viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    contactLongPress(viewHolder.address.getText().toString(),
                            viewHolder.name.getText().toString());
                    return true;
                }
            });
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(ContactViewHolder holder, int position) {
            contactCursor.moveToPosition(position);
            holder.address.setText(contactCursor.getString(0));
            String name = contactCursor.getString(1);
            if (name == null || name.equals(""))
                name = "Anonymous";
            holder.name.setText(name);
            long n = contactCursor.getLong(2);
            if (n > 0) {
                holder.badge.setVisibility(View.VISIBLE);
                holder.count.setText("" + n);
            } else {
                holder.badge.setVisibility(View.GONE);
            }
        }

        @Override
        public int getItemCount() {
            return contactCursor != null ? contactCursor.getCount() : 0;
        }
    });

    requestRecycler.setLayoutManager(new LinearLayoutManager(this));
    requestRecycler.setAdapter(new RecyclerView.Adapter<ContactViewHolder>() {
        @Override
        public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            final ContactViewHolder viewHolder = new ContactViewHolder(
                    getLayoutInflater().inflate(R.layout.item_contact_request, parent, false));
            viewHolder.accept.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String addr = viewHolder.address.getText().toString();
                    db.acceptContact(addr);
                    Client.getInstance(getApplicationContext()).startAskForNewMessages(addr);
                    updateContactList();
                }
            });
            viewHolder.decline.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final String address = viewHolder.address.getText().toString();
                    final String name = viewHolder.name.getText().toString();
                    db.removeContact(address);
                    updateContactList();
                    Snackbar.make(findViewById(R.id.drawer_layout), R.string.contact_request_declined,
                            Snackbar.LENGTH_LONG).setAction(R.string.undo, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    db.addContact(address, false, true, name);
                                    updateContactList();
                                }
                            }).show();
                }
            });
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(ContactViewHolder holder, int position) {
            requestCursor.moveToPosition(position);
            holder.address.setText(requestCursor.getString(0));
            String name = requestCursor.getString(1);
            if (name == null || name.equals(""))
                name = "Anonymous";
            holder.name.setText(name);
        }

        @Override
        public int getItemCount() {
            return requestCursor != null ? requestCursor.getCount() : 0;
        }
    });

    tabLayout = (TabLayout) findViewById(R.id.tabLayout);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
    viewPager.setAdapter(new PagerAdapter() {
        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(final ViewGroup container, int position) {
            View v = position == 0 ? contactPage : requestPage;
            container.addView(v);
            return v;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    });
    tabLayout.setupWithViewPager(viewPager);

    tabLayout.getTabAt(0).setText(R.string.tab_contacts);
    tabLayout.getTabAt(1).setText(R.string.tab_requests);

    for (int i = 0; i < 2; i++) {
        View v = getLayoutInflater().inflate(R.layout.tab_header, null, false);
        ((TextView) v.findViewById(R.id.text)).setText(tabLayout.getTabAt(i).getText().toString());
        ((TextView) v.findViewById(R.id.badge)).setText("");
        v.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        tabLayout.getTabAt(i).setCustomView(v);
    }

    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            if (tab.getPosition() == 1) {
                db.clearNewRequests();
            }
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
        }
    });
    updateContactList();

    handleIntent();
    //  inform();
    listen();
}

From source file:baasi.hackathon.sja.TalkActivity.java

/**
 * ?? ???/* w ww .  ja  v  a2s.  com*/
 * @param word String
 */
private void startTalk(final String word) {
    speech = new TextToSpeech(getBaseContext(), new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status != TextToSpeech.ERROR) {
                speech.setLanguage(Locale.UK);
                speech.speak(word, TextToSpeech.QUEUE_FLUSH, null);
            }
        }
    });
}

From source file:net.bible.service.device.speak.TextToSpeechController.java

private void startSpeakingInitingIfRequired() {
    if (mTts == null) {
        Log.d(TAG, "mTts was null so initialising Tts");

        try {/*from   w  w  w. j  a  v  a 2s.  co m*/
            // Initialize text-to-speech. This is an asynchronous operation.
            // The OnInitListener (second argument) is called after initialization completes.
            mTts = new TextToSpeech(context, this // TextToSpeech.OnInitListener
            );
        } catch (Exception e) {
            Log.e(TAG, "Error initialising Tts", e);
            showError(R.string.error_occurred);
        }
    } else {
        startSpeaking();
    }
}

From source file:com.example.robert.bluetoothnew.BluetoothChatFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);//from   w  w w.java 2s.c  o  m
    // Get local Bluetooth adapter
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    initSingleTonTemp();
    // If the adapter is null, then Bluetooth is not supported
    intiCallWeb();
    toWebPosition();
    if (mBluetoothAdapter == null) {
        FragmentActivity activity = getActivity();
        Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        activity.finish();
    } // No bluetooth service

    tts = new TextToSpeech(getActivity(), new TextToSpeech.OnInitListener() {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onInit(int status) {
            Log.v("abasdasd", "status 123");

            if (status == TextToSpeech.SUCCESS) {

                int result = tts.setLanguage(Locale.TAIWAN);

                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    Log.e("TTS", "This Language is not supported");
                } else {

                }

            } else {
                Log.e("TTS", "Initilization Failed!");
            }
        }
    });
}

From source file:org.envirocar.app.application.service.BackgroundServiceImpl.java

@Override
public void onCreate() {
    logger.info("onCreate " + getClass().getName() + "; Hash: " + System.identityHashCode(this));

    tts = new TextToSpeech(getApplicationContext(), new TextToSpeechListener());

    toastHandler = new Handler();
}

From source file:com.bellman.bible.service.device.speak.TextToSpeechController.java

private void startSpeakingInitingIfRequired() {
    if (mTts == null) {
        Log.d(TAG, "mTts was null so initialising Tts");

        try {// w  ww . j  a  v a2 s .c o m
            // Initialize text-to-speech. This is an asynchronous operation.
            // The OnInitListener (second argument) is called after initialization completes.
            mTts = new TextToSpeech(context, this // TextToSpeech.OnInitListener
            );
        } catch (Exception e) {
            Log.e(TAG, "Error initialising Tts", e);
            showError(R.string.error_occurred, e);
        }
    } else {
        startSpeaking();
    }
}

From source file:com.example.activitydemo.app.service.GameService.java

@Override
public IBinder onBind(Intent intent) {
    Log.d(TAG, "onBind");
    if (mTextToSpeech == null) {
        mTextToSpeech = new TextToSpeech(this, this);
    }//from   w  w  w.j a  va2  s .c o m
    return mBinderService.asBinder();
}