Android TTS onUtteranceCompleted callback isn't getting called - android

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);
}

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.

SpeechRecognizer is just staying on onRmsChanged

package com.example.hp.check2;
import android.content.Intent;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList data;
TextView tv;
Button speakButton;
public SpeechRecognizer sr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
speakButton = (Button) findViewById(R.id.btn_speak);
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(new listener());
tv=(TextView)findViewById(R.id.textView);
data=new ArrayList();
}
class listener implements RecognitionListener
{
#Override
public void onReadyForSpeech(Bundle params) {
Toast.makeText(MainActivity.this, "onReadyForSpeech", Toast.LENGTH_SHORT).show();
}
#Override
public void onBeginningOfSpeech() {
Toast.makeText(MainActivity.this, "onBeginningOfSpeech", Toast.LENGTH_SHORT).show();
}
#Override
public void onRmsChanged(float rmsdB) {
Toast.makeText(MainActivity.this, "onRmsChanged", Toast.LENGTH_SHORT).show();
}
#Override
public void onBufferReceived(byte[] buffer) {
Toast.makeText(MainActivity.this, "onbufferreceived", Toast.LENGTH_SHORT).show();
}
#Override
public void onEndOfSpeech() {
Toast.makeText(MainActivity.this, "onEndOfSpeech", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(int error) {
Toast.makeText(MainActivity.this, "onError", Toast.LENGTH_SHORT).show();
}
#Override
public void onResults(Bundle results) {
String str = new String();
data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < data.size()+10; i++)
{
str += data.get(i)+"S";
}
tv.setText(str);
}
#Override
public void onPartialResults(Bundle partialResults) {
Toast.makeText(MainActivity.this, "onPartialReults", Toast.LENGTH_SHORT).show();
}
#Override
public void onEvent(int eventType, Bundle params) {
Toast.makeText(MainActivity.this, "onEvent", Toast.LENGTH_SHORT).show();
}
}
public void onClick(View v) {
if (v.getId() == R.id.btn_speak)
{
sr.startListening(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH));
}
}
}
When I am running the code,I am just getting the toast of onRmsChanged and nothing else and it continues till I close the application.And there is no method change when I try to speak as there is no new Toast appearing on the screen.I have read about onRmsChanged on internet but didn't get it much.I have granted the permission of microphone but still the problem occurs.Any idea what is going on?

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!");
}
}

Text to speech not working on android device

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);
}
}

Android SpeechRecognizer always returns null

package com.example.voicerec;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
public class MainActivity extends Activity {
private SpeechRecognizer mSpeechRecognizer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizer.setRecognitionListener(new listener());
startrecording();
}
public void startrecording() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
getPackageName());
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
mSpeechRecognizer.startListening(intent);
Log.i("log", "startgooglerec Started");
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mSpeechRecognizer != null) {
mSpeechRecognizer.destroy();
}
}
class listener implements RecognitionListener {
#Override
public void onReadyForSpeech(Bundle params) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int error) {
}
#Override
public void onResults(Bundle results) {
ArrayList<String> matches = results
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
System.out.println("results " + results);
System.out.println("matches " + matches);
}
#Override
public void onPartialResults(Bundle partialResults) {
}
#Override
public void onEvent(int eventType, Bundle params) {
}
}
}
Log:
03-25 09:53:51.489: I/System.out(12149): results Bundle[{results_recognition=null, confidence_scores=null}]
SpeechRecognizer always returns null in onresult, even if i talk also it returns null only, also i dose not stop listening. i can able to here listen to start sound but not stop sound. is there any thing wrong with my code, thanks in advance.

Categories

Resources