Why my TTS does not work? - android

I have the following piece of code:
package audiovisuales.aventuresengulpiyuri;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import util.Utilidades;
public class PaginaPrimera extends AppCompatActivity implements OnInitListener{
private TextToSpeech tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pagina_primera);
if (!Utilidades.verificaConexion(this)){
Utilidades.mostrarVentanaErrorDeConexion(this);
}
else if(Portada.getLecturaAutomatica()){
tts= new TextToSpeech(PaginaPrimera.this, this);
tts.speak(getResources().getString(R.string.primeraPagina), TextToSpeech.QUEUE_FLUSH, null);
}
}
The minimum API I have set is API 19. I have checked that it enters in the else block and it detects the text to tell, but when I execute it doesn't say anything.

You need to check if TTS is available on the device.
First, in your onCreate method have this:
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, REQUEST_DATA_CHECK_CODE);
}
Then in you onActivityResult, check if it is ok to use TTS.
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
mTts = new TextToSpeech(this, this);
} else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(
TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
Then check if the language of the device is available.
if (mTts.isLanguageAvailable(Locale.getDefault()) >= 0) {
mTts.setLanguage(Locale.getDefault());
mTts.speak(textToBeSpoken, TextToSpeech.QUEUE_FLUSH, null);
}
If the language is not available, you may try to install the data for that language or you may change the language.

Related

PAypal android future payment issues

i am trying to create a future payment flow into my android app. I already send to my server the OaUTH2 authentication in my method sendAuthorizationToServer; My question is, what and how should i do next, i know that i have to implement a http request to set the future payment but the documetns in paypal are using curl. what should i do next?
here is my paypal activity:
package studio.brunocasamassa.ajudaaqui.payment;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import com.google.firebase.database.DatabaseReference;
import com.paypal.android.sdk.payments.PayPalAuthorization;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalFuturePaymentActivity;
import com.paypal.android.sdk.payments.PayPalService;
import studio.brunocasamassa.ajudaaqui.R;
import studio.brunocasamassa.ajudaaqui.helper.Base64Decoder;
import studio.brunocasamassa.ajudaaqui.helper.FirebaseConfig;
/**
* Created by bruno on 02/07/2017.
*/
public class PaymentActivity extends AppCompatActivity implements View.OnClickListener{
private static final int REQUEST_CODE_FUTURE_PAYMENT = 123;
private static PayPalConfiguration config = new PayPalConfiguration()
// Start with mock environment. When ready, switch to sandbox (ENVIRONMENT_SANDBOX)
// or live (ENVIRONMENT_PRODUCTION)
.environment(PayPalConfiguration.ENVIRONMENT_NO_NETWORK)
.clientId(PayPalConfig.PAYPAL_CLIENT_ID)
// Minimally, you will need to set three merchant information properties.
// These should be the same values that you provided to PayPal when you registered your app.
.merchantName("Hipster Store")
.merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
.merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));
private ImageButton buttonPay;
private TextView editTextAmount;
private String userKey = Base64Decoder.encoderBase64(FirebaseConfig.getFirebaseAuthentication().getCurrentUser().getEmail());
private DatabaseReference dbUser = FirebaseConfig.getFireBase().child("usuarios").child(userKey);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paypal);
buttonPay = (ImageButton) findViewById(R.id.buttonPay);
editTextAmount = (TextView) findViewById(R.id.editTextAmount);
buttonPay.setOnClickListener(this);
Intent intent = new Intent(this, PayPalService.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startService(intent);
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
PayPalAuthorization auth = data
.getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
if (auth != null) {
String authorization_code = auth.getAuthorizationCode();
Log.i("FuturePaymentExample", authorization_code);
sendAuthorizationToServer(auth);
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("FuturePaymentExample", "The user canceled.");
} else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
Log.i("FuturePaymentExample",
"Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
}
}
private void sendAuthorizationToServer(PayPalAuthorization auth) {
dbUser.child("auth").setValue(auth);
}
public void onFuturePaymentPressed(View pressed) {
Intent intent = new Intent(PaymentActivity.this, PayPalFuturePaymentActivity.class);
// send the same configuration for restart resiliency
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
startActivityForResult(intent, REQUEST_CODE_FUTURE_PAYMENT);
}
public void onFuturePaymentPurchasePressed(View pressed) {
// Get the Client Metadata ID from the SDK
String metadataId = PayPalConfiguration.getClientMetadataId(this);
// TODO: Send metadataId and transaction details to your server for processing with
// PayPal...
dbUser.child("metadata").setValue(metadataId);
}
#Override
public void onDestroy() {
stopService(new Intent(this, PayPalService.class));
super.onDestroy();
}
#Override
public void onClick(View v) {
onFuturePaymentPressed(v);
//onFuturePaymentPurchasePressed(v);
}
}
if someone knows, please tell me, i will be very gratefull
tks,

Zxing barcode integeration: The constructor IntentIntegrator() is undefined

i'm trying to integrate Zxing library, and use the barcode scanner from my app.
so, downloaded the 2 java files IntentIntegrator and IntentResult, put them into this package:
com.google.zxing.integration
where my app is in this package:
com.example.mindstormsgamepad
the code I'm using in my activity is:
package com.example.mindstormsgamepad;
import com.google.zxing.integration.IntentIntegrator;
import com.google.zxing.integration.IntentResult;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.Button;
import android.widget.TextView;
/**
* BarcodeScan Activity
*/
public class BarcodeScanActivity extends CommonActivity implements OnClickListener{
/** Debug */
protected String TAG_SUB = "BarcodeScanActivity";
private Button scanBtn;
private TextView formatTxt, contentTxt;
#Override
public void onCreate(Bundle savedInstanceState) {
initTabSub( TAG_SUB );
log_d( "onCreate" );
super.onCreate( savedInstanceState );
/* set the layout on the screen */
View view = getLayoutInflater().inflate( R.layout.activity_barcode_scan, null );
setContentView( view );
/* Initialization of Bluetooth */
initManager( view );
setTitleName( R.string.activity_barcodescan );
initButtonBack();
initInputDeviceManager();
Toast.makeText(BarcodeScanActivity.this, "QR Scan!", Toast.LENGTH_SHORT).show();
/* Initialization of Scanning */
scanBtn = (Button)findViewById(R.id.scan_button);
formatTxt = (TextView)findViewById(R.id.scan_format);
contentTxt = (TextView)findViewById(R.id.scan_content);
scanBtn.setOnClickListener(this);
}
// --- onCreate end ---
/**
* === onResume ===
*/
#Override
public void onResume() {
log_d( "onResume()" );
super.onResume();
startService();
mInputDeviceManager.register();
}
/**
* === onPause ===
*/
#Override
public void onPause() {
log_d( "onPause()" );
super.onPause();
sendStop();
mInputDeviceManager.unregister();
}
#Override
public void onClick(View v) {
// Start Scan
if(v.getId()==R.id.scan_button){
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanContent);
}else{
Toast toast = Toast.makeText(getApplicationContext(),
"No Barcode data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
but I'm getting this error,
The constructor IntentIntegrator(BarcodeScanActivity) is undefined
and
The method initiateScan(Activity) in the type IntentIntegrator is not applicable for the arguments ()
on these lines:
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
I'm new to android programming,
how to solve this problem?
thanks for your help.
Try This :
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE,PRODUCT_MODE");
startActivityForResult(intent, 0);
For Result Do the code in onActivityResult method
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
Toast.makeText(getActivity(), "result ", 1000).show();
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
//do code here
}
else if (resultCode == RESULT_CANCELED) {
//do code here
}
}
This means your Activity does not ultimately extend android.app.Activity. see what CommonActivity extends. Otherwise maybe you somehow have an old or wrong copy of the IntentIntegrator.

my text-to-speech android app stopped working when i put it in a tab

I have a text-to-speech app and it works perfectly. thing is I have to put it in a tab, and the tabs works fine. But when I put the tts inside the tab, it doesn't work anymore. I already changed class name, layout to view and package, everything else's pretty unchangeable except the variables of course. Layout's fine. And unluckily I really have to put it in a tab. but the worst part is that it doesn't show any errors. Even try catch can't catch anything. So I suppose it's a kind of a logical error, and it sucked all the logic in my head. Lol. I checked the main activity, where this activity is called, and manifest, they're clean. So, here's the code:
package leytocz.add.andriod;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class nptab extends Activity implements TextToSpeech.OnInitListener{
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nptab);
tts=new TextToSpeech(this,this);
btnSpeak=(Button) findViewById(R.id.btnSpeak);
txtText=(EditText) findViewById(R.id.txtText);
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
speakOut();
}
});
}
#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) {
Log.e("TTS","This Language is not supported");
} else {
btnSpeak.setEnabled(true);
speakOut();
}
} else {
Log.e("TTS", "Initialization Failed!");
}
}
private void speakOut() {
String text=txtText.getText().toString();
tts.speak(text,TextToSpeech.QUEUE_FLUSH, null);
}
}
Correct.
static TextToSpeech mTTS;
onCreate():
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
onActivityResult:
if (requestCode == MY_DATA_CHECK_CODE && !mTTSInitialized)
{
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS)
{
// success, create the TTS instance
mTTS = new TextToSpeech(this, (OnInitListener) this);
if (mTTS!=null)
mTTSInitialized = true;
}
else
{
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(
TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
Getter:
public static TextToSpeech getmTTS() {
return mTTS;
}
All of this is placed in the TabHost itself.
Dont need to write this much code in your activity just write this line alone,i also faced this problem finally i got this solution.
Change this one
tts=new TextToSpeech(this,this); --this is your code
You change like this
tts=new TextToSpeech(getParent(),this);
It will work perfectly for me

Recognizer Intent not able to define its constants

I am using the activity, voicerecognition.java, provided by Google to allow the user to choose a language, talk into the handset, and view what they have just said. It works when I take out all the language constants, but when I put the language options in, I get errors.
For example:
The method getVoiceDetailsIntent(VoiceRecognition) is undefined for the type
EXTRA_SUPPORTED_LANGUAGES cannot be resolved or is not a field
EXTRA_LANGUAGE_PREFERENCE cannot be resolved or is not a field
The method run() of type new Runnable(){} must override a superclass method
I thought I might just need to update the SDK or something but everything is up to date. I have no idea what is wrong since I copied the activity exactly as is on the link provided.
package com.sample.voicerecog;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Handler;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class VoiceRecognition extends Activity implements OnClickListener {
private static final String TAG = "VoiceRecognition";
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
private ListView mList;
private Handler mHandler;
private Spinner mSupportedLanguageView;
/**
* Called with the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
// Inflate our UI from its XML layout description.
setContentView(R.layout.voice_recognition);
// Get display items for later interaction
Button speakButton = (Button) findViewById(R.id.btn_speak);
mList = (ListView) findViewById(R.id.list);
mSupportedLanguageView = (Spinner) findViewById(R.id.supported_languages);
// Check to see if a recognition activity is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
speakButton.setOnClickListener(this);
} else {
speakButton.setEnabled(false);
speakButton.setText("Recognizer not present");
}
// Most of the applications do not have to handle the voice settings. If the application
// does not require a recognition in a specific language (i.e., different from the system
// locale), the application does not need to read the voice settings.
refreshVoiceSettings();
}
/**
* Handle the click on the start recognition button.
*/
public void onClick(View v) {
if (v.getId() == R.id.btn_speak) {
startVoiceRecognitionActivity();
}
}
/**
* Fire an intent to start the speech recognition activity.
*/
private void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// Display an hint to the user about what he should say.
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
// Given an hint to the recognizer about what the user is going to say
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
// Specify how many results you want to receive. The results will be sorted
// where the first result is the one with higher confidence.
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
// Specify the recognition language. This parameter has to be specified only if the
// recognition has to be done in a specific language and not the default one (i.e., the
// system locale). Most of the applications do not have to set this parameter.
if (!mSupportedLanguageView.getSelectedItem().toString().equals("Default")) {
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
mSupportedLanguageView.getSelectedItem().toString());
}
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
/**
* Handle the results from the recognition activity.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
// Fill the list view with the strings the recognizer thought it could have heard
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
matches));
}
super.onActivityResult(requestCode, resultCode, data);
}
private void refreshVoiceSettings() {
Log.i(TAG, "Sending broadcast");
sendOrderedBroadcast(RecognizerIntent.getVoiceDetailsIntent(this), null,
new SupportedLanguageBroadcastReceiver(), null, Activity.RESULT_OK, null, null);
}
private void updateSupportedLanguages(List<String> languages) {
// We add "Default" at the beginning of the list to simulate default language.
languages.add(0, "Default");
SpinnerAdapter adapter = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item, languages.toArray(
new String[languages.size()]));
mSupportedLanguageView.setAdapter(adapter);
}
private void updateLanguagePreference(String language) {
TextView textView = (TextView) findViewById(R.id.language_preference);
textView.setText(language);
}
/**
* Handles the response of the broadcast request about the recognizer supported languages.
*
* The receiver is required only if the application wants to do recognition in a specific language.
*/
private class SupportedLanguageBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, final Intent intent) {
Log.i(TAG, "Receiving broadcast " + intent);
final Bundle extra = getResultExtras(false);
if (getResultCode() != Activity.RESULT_OK) {
mHandler.post(new Runnable() {
#Override
public void run() {
showToast("Error code:" + getResultCode());
}
});
}
if (extra == null) {
mHandler.post(new Runnable() {
#Override
public void run() {
showToast("No extra");
}
});
}
if (extra.containsKey(RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES)) {
mHandler.post(new Runnable() {
#Override
public void run() {
updateSupportedLanguages(extra.getStringArrayList(
RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES));
}
});
}
if (extra.containsKey(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE)) {
mHandler.post(new Runnable() {
#Override
public void run() {
updateLanguagePreference(
extra.getString(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE));
}
});
}
}
private void showToast(String text) {
Toast.makeText(VoiceRecognition.this, text, 1000).show();
}
}
}
Any help is appreciated
It appears that your project is at a lower API level than level 8. To fix this, if you are using Eclipse, right click on your project and click properties. Choose Android from the menu on the left, and select a different project build target. If you don't find one at level 8 or higher, click on Window -> Android SDK Manager and install one. You can see what features of RecognizerIntent are available at the various API levels here.

Cannot start TTS (Text to Speech)

Ok basically I have everything set up and I have set up my onClick method many times, but this time it is set up in my main.xml file
<Button
android:layout_alignParentRight="true"
android:layout_height="40dip"
android:layout_width="80dip"
android:id="#+id/speak"
android:enabled="true"
android:visible="true"
android:text="Speak" >
</Button>
obviously it has other things to define its layout but that is one of the xml layouts inside my button, and for some reason every time I click on the button, it just closes the entire application, Why is that?
also If I set it up to add a onClickListener then the button just does nothing.
I would set up my onClick listener like this
speak.setOnClickListener(this);
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.speak:
doSpeak();
break;
}
}
and it still doesnt work.... So i just dont know what I am doing wrong
package com.write.it;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Speech extends Activity implements OnInitListener {
private EditText words = null;
private Button speakBtn = null;
private static final int REQ_TTS_STATUS_CHECK = 0;
private static final String TAG = "TTS Demo";
private TextToSpeech mTts = null;
private MediaPlayer player = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
words = (EditText)findViewById(R.id.wordsToSpeak);
speakBtn = (Button)findViewById(R.id.speak);
// Check to be sure that TTS exists and is okay to use
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, REQ_TTS_STATUS_CHECK);
}
public void doButton(View view) {
switch(view.getId()) {
case R.id.speak:
mTts.speak(words.getText().toString(), TextToSpeech.QUEUE_ADD, null);
break;
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQ_TTS_STATUS_CHECK) {
switch (resultCode) {
case TextToSpeech.Engine.CHECK_VOICE_DATA_PASS:
// TTS is up and running
mTts = new TextToSpeech(this, this);
Log.v(TAG, "Pico is installed okay");
break;
case TextToSpeech.Engine.CHECK_VOICE_DATA_BAD_DATA:
case TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_DATA:
case TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_VOLUME:
// missing data, install it
Log.v(TAG, "Need language stuff: " + resultCode);
Intent installIntent = new Intent();
installIntent.setAction(
TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
break;
case TextToSpeech.Engine.CHECK_VOICE_DATA_FAIL:
default:
Log.e(TAG, "Got a failure. TTS apparently not available");
}
}
else {
// Got something else
}
}
public void onInit(int status) {
// Now that the TTS engine is ready, we enable buttons
if( status == TextToSpeech.SUCCESS) {
speakBtn.setEnabled(true);
}
}
#Override
public void onPause()
{
super.onPause();
// if we're losing focus, stop playing
if(player != null) {
player.stop();
}
// if we're losing focus, stop talking
if( mTts != null)
mTts.stop();
}
#Override
public void onDestroy()
{
super.onDestroy();
if(player != null) {
player.release();
}
if( mTts != null) {
mTts.shutdown();
}
}
}
I mean am i not setting the volume or setting or telling it to speak?!?!?, am I not telling it to do something it is supposed to do?..... the volume on my phone is on and the media volume is up, I have an HTC evo 4g so it should work.....
here Ill add another one with utterance and the onClick Method
package com.write.it;
import java.util.HashMap;
import java.util.Locale;
import java.util.StringTokenizer;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Speech extends WriteitActivity implements OnInitListener, OnUtteranceCompletedListener {
private EditText words = null;
private Button speakBtn = null;
private static final int REQ_TTS_STATUS_CHECK = 0;
private static final String TAG = "Word Guesser";
private TextToSpeech mTts;
private int uttCount = 0;
private HashMap<String, String> params = new HashMap<String, String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
words = (EditText)findViewById(R.id.wordsToSpeak);
speakBtn = (Button)findViewById(R.id.speak);
speakBtn.setOnClickListener((OnClickListener) this);
mTts.isLanguageAvailable(Locale.US);
// Check to be sure that TTS exists and is okay to use
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, REQ_TTS_STATUS_CHECK);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.speak:
doSpeak();
break;
}
}
public void doSpeak() {
StringTokenizer st = new StringTokenizer(words.getText().toString(),",.");
while (st.hasMoreTokens()) {
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,
String.valueOf(uttCount++));
mTts.speak(getString(R.id.wordsToSpeak), TextToSpeech.QUEUE_ADD, null);
mTts.speak(getString(R.id.wordsToSpeak), TextToSpeech.SUCCESS, null);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQ_TTS_STATUS_CHECK) {
switch (resultCode) {
case TextToSpeech.Engine.CHECK_VOICE_DATA_PASS:
// TTS is up and running
mTts = new TextToSpeech(this, this);
Log.v(TAG, "Pico is installed okay");
break;
case TextToSpeech.Engine.CHECK_VOICE_DATA_BAD_DATA:
case TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_DATA:
case TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_VOLUME:
// missing data, install it
Log.v(TAG, "Need language stuff: " + resultCode);
Intent installIntent = new Intent();
installIntent.setAction(
TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
break;
case TextToSpeech.Engine.CHECK_VOICE_DATA_FAIL:
default:
Log.e(TAG, "Got a failure. TTS not available");
}
}
else {
// Got something else
}
}
public void onInit(int status) {
// Now that the TTS engine is ready, we enable the button
if( status == TextToSpeech.SUCCESS) {
mTts.setOnUtteranceCompletedListener(this);
}
}
public void onPause()
{
super.onPause();
// if we're losing focus, stop talking
if( mTts != null)
mTts.stop();
}
#Override
public void onDestroy()
{
super.onDestroy();
mTts.shutdown();
}
public void onUtteranceCompleted(String uttId) {
Log.v(TAG, "Got completed message for uttId: " + uttId);
Integer.parseInt(uttId);
}
}
There are many things mixed up in your code, especially the part where you check the engine with a StartActivityforResult().
Please see this example of a working TTS: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/TextToSpeechActivity.html
Also you did not assign any ID to the button (apparently?) Could it be, that another button is using the ID?
/edit:
First of all, merge both Activities. If you call onCreate()again, it will override the previous one. Then add implements OnClickListener and replace
speakBtn.setOnClickListener((OnClickListener) this);
with
speakBtn.setOnClickListener(this);
Eclipse will tell you that you need to add an unimplemented method.
If the XML code you copied at the top of your question is all you have to declare that button, then it is missing the id you expect (R.id.speak) in the handler...
I would suggest you add some debug prints in the doButton function see if that gets called correctly before going any further in the text-to-speech and so on.

Categories

Resources