my code:
private static final String TAG = "TextToSpeechDemo";
private TextToSpeech mTts;
private Button mAgainButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.speak);
TextToSpeech mTts = new TextToSpeech(this,this);
// Initialize text-to-speech. This is an asynchronous operation.
// The OnInitListener (second argument) is called after initialization completes.
mTts = new TextToSpeech(this,
this // TextToSpeech.OnInitListener
);
// The button is disabled in the layout.
// It will be enabled upon initialization of the TTS engine.
mAgainButton = (Button) findViewById(R.id.again_button);
mAgainButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sayHello();
}
});
#Override
public void onInit( int status) {
// TODO Auto-generated method stub
// status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
if (status == TextToSpeech.SUCCESS) {
// Set preferred language to US english.
// Note that a language may not be available, and the result will indicate this.
int result = mTts.setLanguage(Locale.US);
// Try this someday for some interesting results.
// int result mTts.setLanguage(Locale.FRANCE);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
// Language data is missing or the language is not supported.
Log.e(TAG, "Language is not available.");
} else {
// Check the documentation for other possible result codes.
// For example, the language may be available for the locale,
// but not for the specified country and variant.
// The TTS engine has been successfully initialized.
// Allow the user to press the button for the app to speak again.
mAgainButton.setEnabled(true);
// Greet the user.
sayHello();
}
}
else {
// Initialization failed.
Log.e(TAG, "Could not initialize TextToSpeech.");
}
}
private void sayHello() {
Bundle extras = getIntent().getExtras();
String filename = extras.getString("filename");
String filecontent = extras.getString("filecontent");
mTts.speak(filecontent,
TextToSpeech.QUEUE_FLUSH, // Drop all pending entries in the playback queue.
null);
}
it is showing 03-03 12:01:21.778: D/SntpClient(61): request time failed: java.net.SocketException: Address family not supported by protocol error!!!
I would take a guess at this. I think, String filename = extras.getString("filename"); should be changed to String filename = extras.getString("file://" + "filename");
Please post relevant logcat output to help everyone understand the problem.
Related
I am developing TextToSpeech in Android. I use the following code and it work fine.
public void EnableTextToSpeech(){
//TextToSpeech
text_to_speech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status == TextToSpeech.SUCCESS){
Log.d(TAG,"TextToSpeech init SUCCESS");
int result = text_to_speech.setLanguage(Locale.US);
text_to_speech.setPitch(1);
text_to_speech.setSpeechRate(1);
if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
Log.d(TAG,"TextToSpeech NOT SUPPORT");
}else {
Log.d(TAG,"TextToSpeech Enable");
String welcome = "Welcome";
text_to_speech.speak(welcome , TextToSpeech.QUEUE_FLUSH,null,"TEST");
}
}else {
Log.d(TAG,"TextToSpeech init FAIL");
}
}
});
}
But I want it to speak the multiple language like Chines and English in one sentence.
Can I set different language like the following code?
text_to_speech.setLanguage(Locale.CHINESE);
text_to_speech.setLanguage(Locale.US);
How to set and speak multiple language in a sentence for TextToSpeech in Android ?
I am trying to add text-to-speech feature to my app, and it is working fine until I updated TTS from Google Play store.
There wasn't any delay to initialize the TTS in onCreate Method.
After the update, it would take 3-5 seconds for this TTS to finish initializing.
Basically, the text-to-speech is not ready until 3-5 seconds later.
Can someone please tell me what I've done wrong?
private HashMap<String, String> TTS_ID = new HashMap<String, String>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.....
.....
TextToSpeech_Initialize();
}
public void TextToSpeech_Initialize() {
TTS_ID.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "UniqueID");
speech = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status == TextToSpeech.SUCCESS) {
speech.setSpeechRate(SpeechRateValue);
speech.speak(IntroSpeech, TextToSpeech.QUEUE_FLUSH, TTS_ID);
}
}
});
}
Thank you very much
Confirmed! This is an issue with Google text to speech engine, if you try any other tts the delay disappears, eg Pico tts.
I have stumbled across this problem before but now I have found a proper solution..
You can initialize TextToSpeach in onCreate() like this:
TextToSpeach textToSpeech = new TextToSpeech(this, this);
but first you need to implement TextToSpeech.OnInitListener, and then you need to override the onInit() method:
#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();
}
}
I also noticed that if you didn't set the language in onInit() there is gonna be a delay!!
And now you can write the method that says the text:
private void speakOut(final String detectedText){
if(textToSpeech !=null){
textToSpeech.stop(); //stop and say the new word
textToSpeech.speak(detectedText ,TextToSpeech.QUEUE_FLUSH, null, null);
}
}
I am developing the app to show some details in English, and when I click the button it speaks out that message in English,text contains numbers also. I want to speech that text in Telugu language, Is there any way to do that.The default android tts not supports Telugu language , how to use external tts engines in android applications. Please help me on this, Thank you.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
btnSpeak = (Button) findViewById(R.id.btnSpeak);
txtText = (EditText) findViewById(R.id.txtText);
// button on click event
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
speakOut();
}
});
}
// shutdown tts when activity destroy
#Override
public void onDestroy() {
// Don't forget to shutdown!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
// It will called before TTS started
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
// check status for TTS is initialized or not
if (status == TextToSpeech.SUCCESS) {
// if TTS initialized than set language
result = tts.setLanguage(Locale.US);
// tts.setPitch(5); // you can set pitch level
// tts.setSpeechRate(); //you can set speech speed rate
// check language is supported or not
// check language data is available or not
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(this, "Missing data", Toast.LENGTH_LONG).show();
// disable button
btnSpeak.setEnabled(false);
} else {
// if all is good than enable button convert text to speech
btnSpeak.setEnabled(true);
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
// call this method to speak text
private void speakOut() {
String text = txtText.getText().toString();
if (result != tts.setLanguage(Locale.US)) {
Toast.makeText(getApplicationContext(), "Enter right Words...... ",
Toast.LENGTH_LONG).show();
} else {
// speak given text
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
u have to set locale for that in speak out method
NOTE: phone and eclipse should support your locale
I've been given access to the blogger API, I've confirmed that on my developer console.
I've also written some code to perform oAuth2 with Google Play Services using some of the code below.
String SCOPE ="oauth2:https://www.googleapis.com/auth/blogger";
GoogleAuthUtil.getToken(context, "myEmail#gmail.com", mScope);
It returns a token. As it should.
However, once I try to access the api using the token i get a error.
Unexpected response code 403 for https://www.googleapis.com/blogger/v3/users/self/blogs
Here is my request:
And here is my response:
Here is my BaseActivity.java code that gets the token:
public class BaseActivity extends Activity {
static final int REQUEST_CODE_PICK_ACCOUNT = 1000;
static final int REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR = 1001;
static final int REQUEST_CODE_RECOVER_FROM_AUTH_ERROR = 1002;
private static final String SCOPE ="oauth2:https://www.googleapis.com/auth/blogger";
private String mEmail; // Received from newChooseAccountIntent(); passed to getToken()
public ProgressDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDialog = new ProgressDialog(this);
login();
}
public void login() {
pickUserAccount();
}
private void pickUserAccount() {
String[] accountTypes = new String[]{"com.google"};
Intent intent = AccountPicker.newChooseAccountIntent(null, null, accountTypes, false, null, null, null, null);
startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
// Receiving a result from the AccountPicker
if (resultCode == RESULT_OK) {
mEmail = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
// With the account name acquired, go get the auth token
getToken();
} else if (resultCode == RESULT_CANCELED) {
// The account picker dialog closed without selecting an account.
// Notify users that they must pick an account to proceed.
Toast.makeText(this, "Pick Account", Toast.LENGTH_SHORT).show();
}
} else if ((requestCode == REQUEST_CODE_RECOVER_FROM_AUTH_ERROR ||
requestCode == REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR)
&& resultCode == RESULT_OK) {
// Receiving a result that follows a GoogleAuthException, try auth again
getToken();
}
}
private void getToken() {
if (mEmail == null) {
pickUserAccount();
} else {
if (isDeviceOnline()) {
new getTokenTask(BaseActivity.this, mEmail, SCOPE).execute();
} else {
Toast.makeText(this, "Not online", Toast.LENGTH_LONG).show();
}
}
}
/**
* This method is a hook for background threads and async tasks that need to
* provide the user a response UI when an exception occurs.
*/
public void handleException(final Exception e) {
// Because this call comes from the AsyncTask, we must ensure that the following
// code instead executes on the UI thread.
runOnUiThread(new Runnable() {
#Override
public void run() {
if (e instanceof GooglePlayServicesAvailabilityException) {
// The Google Play services APK is old, disabled, or not present.
// Show a dialog created by Google Play services that allows
// the user to update the APK
int statusCode = ((GooglePlayServicesAvailabilityException)e).getConnectionStatusCode();
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(statusCode, BaseActivity.this, REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
dialog.show();
} else if (e instanceof UserRecoverableAuthException) {
// Unable to authenticate, such as when the user has not yet granted
// the app access to the account, but the user can fix this.
// Forward the user to an activity in Google Play services.
Intent intent = ((UserRecoverableAuthException)e).getIntent();
startActivityForResult(intent, REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR);
}
}
});
}
public boolean isDeviceOnline() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
} else {
return false;
}
}
public class getTokenTask extends AsyncTask{
Activity mActivity;
String mScope;
String mEmail;
getTokenTask(Activity activity, String name, String scope) {
this.mActivity = activity;
this.mScope = scope;
this.mEmail = name;
}
#Override
protected Object doInBackground(Object[] params) {
try {
String token = fetchToken();
Preferences.saveString(Constants.KEY_BLOGGER_TOKEN, token);
} catch (IOException e) {
// The fetchToken() method handles Google-specific exceptions,
// so this indicates something went wrong at a higher level.
// TIP: Check for network connectivity before starting the AsyncTask.
}
return null;
}
/**
* Gets an authentication token from Google and handles any
* GoogleAuthException that may occur.
*/
protected String fetchToken() throws IOException {
try {
return GoogleAuthUtil.getToken(mActivity, mEmail, mScope);
} catch (UserRecoverableAuthException userRecoverableException) {
// GooglePlayServices.apk is either old, disabled, or not present
// so we need to show the user some UI in the activity to recover.
((BaseActivity)mActivity).handleException(userRecoverableException);
} catch (GoogleAuthException fatalException) {
// Some other type of unrecoverable exception has occurred.
// Report and log the error as appropriate for your app.
}
return null;
}
}
}
I've been banging my head against the wall on this one. Anyone have any ideas?
Finally figured it out.
My build.gradle file somehow ended up having a different Application ID than my manifest. I changed it so they both match the manifest, and boom! it worked.
I have gone through almost all the links related to this topic but haven't found any suitable answer. I am trying to build a basic text to speech application. It works perfectly fine on the emulator. But when i run it on my phone, it shows language not supported.
I guess this has something to do with the locale. The default locale set in my phone is en_US
My code is as follows:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
btnSpeak = (Button) findViewById(R.id.btnSpeak);
txtText = (EditText) findViewById(R.id.txtText);
btnSpeak.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Method yet to be defined
speakOut();
}
});
}
public void onInit(int status) {
// TODO Auto-generated method stub
// TTS is successfully initialized
if (status == TextToSpeech.SUCCESS) {
// Setting speech language
// System.out.println(Locale.getAvailableLocales());
int result = tts.setLanguage(Locale.ENGLISH);
// int result = tts.setLanguage(Locale.getDefault());
// If your device doesn't support language you set above
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
// Cook simple toast message with message
Toast.makeText(this, "Language not supported",
Toast.LENGTH_LONG).show();
Log.e("TTS", "Language is not supported");
} else {
btnSpeak.setEnabled(true);
}
// TTS is not initialized properly
} else {
Toast.makeText(this, "TTS Initilization Failed", Toast.LENGTH_LONG)
.show();
Log.e("TTS", "Initilization Failed");
}
}
private void speakOut() {
// Get the text typed
String text = txtText.getText().toString();
// If no text is typed, tts will read out 'You haven't typed text'
// else it reads out the text you typed
if (text.length() == 0) {
tts.speak("You haven't typed text", TextToSpeech.QUEUE_FLUSH, null);
} else {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
public void onDestroy() {
// Don't forget to shutdown!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
even if i use int result = tts.setLanguage(Locale.getDefault()); instead of Locale.ENGLISH, it shows the same language not supported message
LOGCAT ERROR:
02-26 16:24:57.492: I/TextToSpeech.java(23356): initTts() successfully bound to service
02-26 16:24:58.015: E/TTS(23356): Language is not supported
I am running this on my phone- Samsung Galaxy-Y (GT-S5360) with Android version 2.3.6
found a solution myself. the problem was that the locales available on the android default tts engine did not match those on my phone.
i installed another tts engine and it works perfectly fine with it.