Text to speech not working on android device - android

Below is my code.I am unable to hear the voice in my kitkat device.Toast is appearing but voice is not playing.I am following this tutorial
https://www.tutorialspoint.com/android/android_text_to_speech.htm
package com.example.insert;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
import android.widget.Toast;
import android.util.Log;
import java.lang.Object;
public class SecondActivity extends AppCompatActivity {
TextToSpeech t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
String emailid;
emailid = "Hi,say your email id";
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = t1.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(getApplicationContext(), "This language is not supported", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Initialization failed", Toast.LENGTH_SHORT).show();
}
}
});
// Toast.makeText(getApplicationContext(), emailid, Toast.LENGTH_SHORT).show();
t1.speak(emailid, TextToSpeech.QUEUE_FLUSH, null);
}
#Override
protected void onDestroy() {
super.onDestroy();
// Don't forget to shutdown tts!
if (t1 != null) {
Log.e("TTS","speech on destroy");
t1.stop();
t1.shutdown();
}
}
}
I have followed this post on stackoverflow.
Android TTS doesn't speak
But i didn't understand gameover,line and definition_string.
guys help me

Here is my code. this code works on Nexus9.(Locale is Japan)
public class MainActivity extends AppCompatActivity{
static final String TAG = "TTS";
TextToSpeech mTts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String emailid;
emailid = "こんにちは";
mTts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = mTts.setLanguage(Locale.JAPAN);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(getApplicationContext(), "This language is not supported", Toast.LENGTH_SHORT).show();
}
else{
Log.v("TTS","onInit succeeded");
speak(emailid);
}
} else {
Toast.makeText(getApplicationContext(), "Initialization failed", Toast.LENGTH_SHORT).show();
}
}
});
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
void speak(String s){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Log.v(TAG, "Speak new API");
Bundle bundle = new Bundle();
bundle.putInt(TextToSpeech.Engine.KEY_PARAM_STREAM, AudioManager.STREAM_MUSIC);
mTts.speak(s, TextToSpeech.QUEUE_FLUSH, bundle, null);
} else {
Log.v(TAG, "Speak old API");
HashMap<String, String> param = new HashMap<>();
param.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_MUSIC));
mTts.speak(s, TextToSpeech.QUEUE_FLUSH, param);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
// Don't forget to shutdown tts!
if (mTts != null) {
Log.v(TAG,"onDestroy: shutdown TTS");
mTts.stop();
mTts.shutdown();
}
}
}

It takes some time to initialise. Put the speak code in onClick method. If you trigger that method on button click, it will speak.
someButton.setOnClickListener(new OnClickListener{
onClick(View view){
t1.speak(emailid, TextToSpeech.QUEUE_FLUSH, null);
}
}

I guess problem is with Locale.
Please print logs. try out following code.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
import android.widget.Toast;
public class SecondActivity extends AppCompatActivity {
TextToSpeech t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
String emailid;
emailid="Hi,say your email id";
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status == TextToSpeech.SUCCESS) {
t1.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.d(TAG, "This Language is not supported");
}
}else{
Log.d(TAG, "Initilization Failed!");
}
}
});
Toast.makeText(getApplicationContext(), emailid,Toast.LENGTH_SHORT).show();
t1.speak(emailid, TextToSpeech.QUEUE_FLUSH, null);
}
#Override
protected void onDestroy() {
super.onDestroy();
// Don't forget to shutdown tts!
if (mTextToSpeech != null) {
Log.d(TAG, "speach on destroy");
t1.stop();
t1.shutdown();
}
}

I don't understand why didn't you implement your main Activity class from TextToSpeech.OnInitListener...!
Here's your answer:
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 AndroidTextToSpeechActivity extends Activity implements
TextToSpeech.OnInitListener {
/** Called when the activity is first created. */
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.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();
}
});
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#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", "Initilization Failed!");
}
}
private void speakOut() {
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}

Related

Wait for TextToSpeech onInit() initialization on Android

I am writing a text-to-speech android application. I am refactoring the code and trying to separate TextToSpeech class from an activity to a service so the UI can be updated without blocking, while the audio is playing in the background. However I am not able to wait for the TTS engine to initialize.
When I use
while(isInit==false)
Thread.sleep(1000);
the service never calls the onServiceConnected method.
If anybody knows how to wait for initialization of the TTS engine to complete, and avoid blocking the UI for too long (which causes the application to crash), help would be greatly appreciated!
Here is my service
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.util.HashMap;
import java.util.Locale;
public class MyTTSService extends Service {
private static final String TAG = "Class-MyTTSService";
private TextToSpeech tts;
private boolean isInit = false;
private final IBinder myBinder = new MyBinder();
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "Creating TTS Service");
Context context = this.getApplicationContext();
this.tts = new TextToSpeech(context, onInitListener);
this.tts.setOnUtteranceProgressListener(utteranceProgressListener);
Log.d(TAG, "TTS Service Created");
// why is this blocking everything?
while(!isInitComplete()){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.d(TAG, e.toString());
}
}
}
public boolean isInitComplete(){
return isInit;
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void waitToFinishSpeaking() {
while (tts.isSpeaking()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Log.d(TAG, e.toString());
}
}
}
public void speak(String text, AppCompatActivity appCompatActivity) {
Log.d(TAG, "Speak" + text);
appCompatActivity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
HashMap<String, String> param = new HashMap<>();
param.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_MUSIC));
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
} else {
String utteranceId=this.hashCode() + "";
Bundle bundle = new Bundle();
bundle.putInt(TextToSpeech.Engine.KEY_PARAM_STREAM, AudioManager.STREAM_MUSIC);
tts.speak(text, TextToSpeech.QUEUE_ADD, null, null);
}
}
private UtteranceProgressListener utteranceProgressListener = new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
}
#Override
public void onDone(String utteranceId) {
}
#Override
public void onError(String utteranceId) {
Log.e(TAG, "Error while trying to synthesize sample text");
}
};
private TextToSpeech.OnInitListener onInitListener = 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) {
Log.e("TTS", "This Language is not supported");
} else {
//init success
isInit = true;
Log.d(TAG, "TTS Initialized.");
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
};
#Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "Binding TTS Service");
return myBinder;
}
public class MyBinder extends Binder {
MyTTSService getService() {
return MyTTSService.this;
}
}
#Override
public boolean onUnbind(Intent intent) {
return false;
}
}
And here is my activity
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class ReaderActivity extends AppCompatActivity {
private static final String TAG = "Class-ReaderActivity";
EditText textBox;
ArrayList<String> sentences = new ArrayList<String>();
MyTTSService tts;
boolean isBound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reader);
textBox = (EditText) findViewById(R.id.readerTextArea);
Intent intentExtras = getIntent();
Bundle extrasBundle = intentExtras.getExtras();
sentences = extrasBundle.getStringArrayList("sentences");
textBox.setText(sentences.toString(), TextView.BufferType.NORMAL);
textBox.setKeyListener(null);
}
#Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, MyTTSService.class);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
Log.d(TAG, "Waiting to bind to service");
}
public void readSentences(){
for(String sentence : sentences){
Log.d(TAG +"Sencence", sentence);
//updateUI(sentence);
tts.speak(sentence, this);
tts.waitToFinishSpeaking();
}
}
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyTTSService.MyBinder binder = (MyTTSService.MyBinder) service;
tts = binder.getService();
isBound = true;
readSentences();
}
#Override
public void onServiceDisconnected(ComponentName name) {
isBound = false;
}
};
}
I found the solution. Remove the existing wait loop from MyTTSService.onCreate().
Place the following at the end of the onServiceConnected method
new Thread(new Runnable() {
public void run(){
readSentences();
}
}).start();
Then add a method to MyTTSService
public boolean isInit(){
return isInit;
}
In some circumstances the tts module may need to be reinitialised. Add the following to TextToSpeech.OnInitListener.OnInit in the cases where initialisation is unsuccessful.
isInit = false;
Then finally add the following to the readsentences method
while(!tts.isInit()){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.d(TAG, e.toString());
}
}
tts.speak(sentence, this);
With these changes the TTS module initialises, audio works, the Activity loads and the UI can be refreshed while audio is playing.
This should finally put the issue (which has been asked several times but never resolved) to bed for good.

java.lang.exception microsoft-translator-api Error retreiving translation: permission denied (missing internet permission?)

Hi All i am new to Android and trying to build an English to German translator and i am getting the above error when i run this app on the mobile screen.
package com.exmaple.android.lang_trans;
import java.util.Locale;
import android.app.Activity;
import android.os.AsyncTask;
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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.exmaple.android.lang_trans.R;
import com.memetix.mst.language.Language;
import com.memetix.mst.translate.Translate;
public class MainActivity extends Activity implements OnInitListener {
private TextToSpeech tts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
((Button) findViewById(R.id.bSpeak)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
speakOut(((TextView) findViewById(R.id.tvTranslatedText)).getText().toString());
}
});
((Button) findViewById(R.id.bTranslate)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
class bgStuff extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
if (params.length > 0) {
return translate(params[0]);
}
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
return null;
}
#Override
protected void onPostExecute(String result) {
((TextView) findViewById(R.id.tvTranslatedText)).setText(result);
}
}
new bgStuff().execute(((EditText) findViewById(R.id.etUserText)).getText().toString());
}
});
}
public String translate(String text) throws Exception {
// Set the Client ID / Client Secret once per JVM. It is set statically and applies to all services
Translate.setClientId("CLIENT ID"); //Change this
Translate.setClientSecret("CLIENT SECRET"); //change
String translatedText = "";
translatedText = Translate.execute(text, Language.GERMAN);
return translatedText;
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.GERMAN);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
//speakOut("Ich");
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut(String text) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
The error says that you didn't request permission to access the internet
in your manifest you should add this line
<uses-permission android:name="android.permission.INTERNET" />
under the <manifest block

TarsosDSP PitchDetection Issue

I am using the audiodispatcher from the TarsosDSPlibrary.
The pitchdetection is used to detect sounds from the mic. Once detected, it switches to the next activity (which is a Maths quiz). After completing the quiz on the next activity, it returns to this activity and starts the process all over again.
What is bugging me is that my APP is working 90% of the time when using the pitchdetection function. However, sometimes it doesn't work and throws an error as follows:
E/AudioRecord: start() status -38
and the app no longers switches to the next activity.
package com.humanfactorsandappliedcognitionlab.research.mathsapp;
import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.RunnableFuture;
import be.tarsos.dsp.AudioDispatcher;
import be.tarsos.dsp.AudioEvent;
import be.tarsos.dsp.io.android.AudioDispatcherFactory;
import be.tarsos.dsp.pitch.PitchDetectionHandler;
import be.tarsos.dsp.pitch.PitchDetectionResult;
import be.tarsos.dsp.pitch.PitchProcessor;
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
MediaPlayer notifySound;
MediaPlayer endSound;
AudioDispatcher dispatcherMAIN;
PitchProcessor pitchProcessorMAIN;
public boolean isListening = false;
TextToSpeech tts;
private int sensitivity = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notifySound = MediaPlayer.create(this, R.raw.samsung);
endSound = MediaPlayer.create(this, R.raw.ding);
OPTION = dbHandler.getOPTION();
tts = new TextToSpeech(this, this);
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run(){
}
});
}
#Override
public void onDone(String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run(){
startListenToTalk();
}
});
}
#Override
public void onError(String utteranceId) {
}
});
}
private void speakOut() {
Log.e("TTS", "SPEAKING...");
String text = "Please Say Continue to Proceed ";
HashMap<String, String> map = new HashMap<String, String>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "");
tts.speak(text, TextToSpeech.QUEUE_FLUSH, map);
}
private void startListenToTalk() {
dispatcherMAIN = AudioDispatcherFactory.fromDefaultMicrophone(22050, 1024, 0);
pitchProcessorMAIN = new PitchProcessor(PitchProcessor.PitchEstimationAlgorithm.FFT_YIN, 22050, 1024, new PitchDetectionHandler() {
#Override
public void handlePitch(PitchDetectionResult pitchDetectionResult,
AudioEvent audioEvent) {
final float pitchInHz = pitchDetectionResult.getPitch();
runOnUiThread(new Runnable() {
#Override
public void run() {
ImageButton buttonOK = (ImageButton) findViewById(R.id.buttonOK);
TextView textINPUT = (TextView)findViewById(R.id.textINPUT);
if (pitchInHz > sensitivity) {
Log.e("pitch : ", pitchInHz + "");
if (isListening) {
try {
dispatcherMAIN.stop();
Intent gotoMaths = new Intent(MainActivity.this, MathsActivity.class);
startActivity(gotoMaths);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
}
});
dispatcherMAIN.addAudioProcessor(pitchProcessorMAIN);
new Thread(dispatcherMAIN, "Audio Dispatcher").start();
isListening = true;
}
#Override
protected void onPause() {
super.onPause();
if (notifySound != null) {
notifySound.release();
}
if (endSound != null) {
endSound.release();
}
if (isListening) {
try {
dispatcherMAIN.stop();
} catch (Exception e) {
e.printStackTrace();
}
isListening = false;
}
finish();
}
#Override
public void onStop(){
super.onStop();
if (tts != null) {
tts.shutdown();
}
}
#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 {
if(OPTION == "3") {
speakOut();
}
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}

Can't set TTS's paras via button

I tried to set TTS's paras such as pitch and speech rate by pressing a button, but somehow nothing changes when I pressed it...
See the code following, what I planned is that once I press the button SetPara, the _pitch and _rate will be set to 0.5, and
tts.setPitch(_pitch);
tts.setSpeechRate(_rate);
will set TTS's pitch and speech rate to 0.5, but the problem now is that after I pressed the SetPara button the pitch and speech rate didn't change...
Please help me out :))))
package com.example.text2speechtrail;
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 MainActivity extends Activity implements
TextToSpeech.OnInitListener {
/** Called when the activity is first created. */
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;
private Button btnSetPara;
private EditText getPitch;
private EditText getRate;
public float _pitch;
public float _rate;
String _string_pitch = null;
String _string_rate = null;
#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);
btnSetPara = (Button) findViewById(R.id.setPara);
txtText = (EditText) findViewById(R.id.txtText);
getPitch = (EditText) findViewById(R.id.getPitch);
getRate = (EditText) findViewById(R.id.getRate);
btnSetPara.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SetPara();
}
});
// button on click event
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
speakOut();
}
});
}
public void SetPara(){
_pitch = (float) 0.5;
_rate = (float) 0.5;
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.ENGLISH);
tts.setPitch(_pitch);
tts.setSpeechRate(_rate);
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", "Initilization Failed!");
}
}
private void speakOut() {
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
You need to set on click listener for your btnSetPara button
btnSetPara.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SetPara();
}
});
You do not need the param View in setPara
public void SetPara(){
_pitch = (float) 0.5;
_rate = (float) 0.5;
if (tts != null) {
tts.setPitch(_pitch);
tts.setSpeechRate(_rate);
}
}
private void speakOut() {
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}

Android TTS onUtteranceCompleted callback isn't getting called

I am trying to get the Android TTS API to read my "utterance" and then call the onUtteranceCompleted() listener unsuccessfully. I've registered my TTS object and it returns SUCCESS, so I can't figure out for the life of me why my callback isn't getting called.
I've tried searching for help, but it seems others have difficulty with this too. Am I missing something simple?
Thanks for any help you can offer.
package com.test.mytts;
import java.util.HashMap;
import android.app.Activity;
import android.media.AudioManager;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.widget.TextView;
import android.widget.Toast;
public class MyTTS extends Activity implements OnInitListener, OnUtteranceCompletedListener
{
TextView tv;
private TextToSpeech _tts;
#Override
public void onCreate(Bundle savedInstanceState)
{
tv = new TextView(this);
tv.setText("MyTTS: ");
super.onCreate(savedInstanceState);
setContentView(tv);
_tts = new TextToSpeech(this, this);
}
#Override
public void onInit(int status)
{
HashMap<String, String> myHashAlarm = new HashMap<String, String>();
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_NOTIFICATION));
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "test");
if (status == TextToSpeech.SUCCESS)
{
Toast.makeText(this, "Trying to speak...", Toast.LENGTH_SHORT).show();
int result = _tts.setOnUtteranceCompletedListener(this);
tv.append(String.valueOf(result));
_tts.setSpeechRate((float) .5);
_tts.speak("Testing one, two, three", TextToSpeech.QUEUE_ADD, myHashAlarm);
}
else
Toast.makeText(this, "Failed to initialize TTS.", Toast.LENGTH_SHORT).show();
}
#Override
public void onUtteranceCompleted(String utteranceId)
{
Toast.makeText(this, "onUtteranceCompleted", Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy()
{
super.onDestroy();
_tts.shutdown();
}
}
Call the setOnUtteranceCompletedListener inside the onInit function of the tts object.
If you want to make any changes to the UI on the call of the onUtteranceCompleted function, add the code inside a runOnUIThread method.
And do remember to add the Hashmap param value while calling the speak() function
Example :
TextToSpeech tts= new TextToSpeech(context, new OnInitListener() {
#Override
public void onInit(int status) {
mTts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {
#Override
public void onUtteranceCompleted(String utteranceId) {
runOnUiThread(new Runnable() {
#Override
public void run() {
//UI changes
}
});
}
});
}
});
HashMap<String, String> params = new HashMap<String, String>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"stringId");
tts.speak("Text to Speak",TextToSpeech.QUEUE_FLUSH, params);
I believe that unless you specify an utterance with an id, like:
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utteranceid);
your utterance completed method will not be called.
in this case, map is the Hashmap you pass to the engine when you speak.
this will work for you on API Level >=15
import java.util.HashMap;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.UtteranceProgressListener;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnInitListener{
private static final int CHECK_TTS_DATA = 0X123;
protected static final String TAG = MainActivity.class.getSimpleName();
private TextToSpeech textToSpeech;
private Button buttonSayIt;
private EditText editTextTts;
String tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonSayIt=(Button) findViewById(R.id.buttonSayIt);
editTextTts=(EditText) findViewById(R.id.editTextTts);
buttonSayIt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tts=editTextTts.getText().toString();
Log.d(TAG, tts);
speach(tts,"you_utterance_id");
}
});
//check for TTs data
Intent checkTtsDataIntent=new Intent();
checkTtsDataIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTtsDataIntent, CHECK_TTS_DATA);
}
protected void speach(String tts,String utteranceId) {
HashMap<String, String> params = new HashMap<String, String>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,utteranceId);
textToSpeech.speak(tts,TextToSpeech.QUEUE_FLUSH,params);
}
#Override
public void onInit(int status) {
if(status==TextToSpeech.SUCCESS){
if(textToSpeech.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE){
textToSpeech.setLanguage(Locale.US);
}
}else if(status==TextToSpeech.ERROR){
Toast.makeText(this, "Sorry Text To Speach faild", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==CHECK_TTS_DATA){
if(resultCode==TextToSpeech.Engine.CHECK_VOICE_DATA_PASS){
textToSpeech=new TextToSpeech(this, this);
textToSpeech.setOnUtteranceProgressListener(utteranceProgressListener);
}else{
Intent installTtsIntent=new Intent();
installTtsIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installTtsIntent);
}
}
}
UtteranceProgressListener utteranceProgressListener=new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
Log.d(TAG, "onStart ( utteranceId :"+utteranceId+" ) ");
}
#Override
public void onError(String utteranceId) {
Log.d(TAG, "onError ( utteranceId :"+utteranceId+" ) ");
}
#Override
public void onDone(String utteranceId) {
Log.d(TAG, "onDone ( utteranceId :"+utteranceId+" ) ");
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
in case anybody is still finding it difficult
Code Snippet
textToSpeech=new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status==TextToSpeech.SUCCESS){
int result=textToSpeech.setLanguage(Locale.ENGLISH);
if (result==TextToSpeech.LANG_MISSING_DATA||result==TextToSpeech.LANG_NOT_SUPPORTED){
Log.i("TextToSpeech","Language Not Supported");
}
textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
Log.i("TextToSpeech","On Start");
}
#Override
public void onDone(String utteranceId) {
Log.i("TextToSpeech","On Done");
}
#Override
public void onError(String utteranceId) {
Log.i("TextToSpeech","On Error");
}
});
}else {
Log.i("TextToSpeech","Initialization Failed");
}
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null,TextToSpeech.ACTION_TTS_QUEUE_PROCESSING_COMPLETED);
}

Categories

Resources