I am trying to make an application that uses Speech to text, and Text to speech.
So the algorithm of this program is:
1 - when the user runs this program, it will call voice Recognition
2 - after getting the input from the user, the program will repeat the same word the user said.
here's my code:
public class MainActivity extends Activity implements TextToSpeech.OnInitListener, OnClickListener {
protected static final int REQUEST_OK = 1234;
String userSay;
TextView text1;
private TextToSpeech tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
findViewById(R.id.button1).setOnClickListener(this);
text1 = (TextView) findViewById(R.id.text1);
tts=new TextToSpeech(this, this);
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onPause(){
if(tts !=null){
tts.stop();
tts.shutdown();
}
super.onPause();
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Log.e("TTS", "Initilization 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 {
String anyThing = " ";
speakIt(anyThing);
}
return;
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakIt(String someThing) {
Log.e("something: ", someThing);
tts.speak(someThing, TextToSpeech.QUEUE_ADD, null);
Log.e("TTS", "called");
}
#Override
public void onClick(View v) {
//Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
//i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
text1.setText(" ");
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName());
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "I'm listen to you...");
try {
startActivityForResult(i, REQUEST_OK);
} catch (Exception e) {
Toast.makeText(this, "Error initializing speech to text engine.", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode==REQUEST_OK && resultCode==-1) {
ArrayList<String> thingsYouSaid = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
userSay = thingsYouSaid.get(0);
}
try {
String FinalValue = getDataMethod(hasil);
text1.setText(FinalValue);
Log.v("Status OK: ", FinalValue);
speakIt(FinalValue);
Log.v("speakIt: ", "called");
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode, data);
}
private String getDataMethod(String num) throws IllegalStateException, IOException {
num = "You say, " + num;
return num;
}
}
But the application won't say anything. And in the logcat I got an error that says:
TextToSpeech(10335): speak failed: not bound to TTS
When before I made this application, I made it in separate parts: Text to Speech, and Speech to Text.
Both of that applications ran normally.
I don't know why this error occurs.
Can anyone help me?
One problem is that you are calling:
speakIt(FinalValue);
inside:
onActivityResult(
while in onPause, you execute:
if(tts !=null){
tts.stop();
tts.shutdown();
}
so once, you open your sub activity, onPause is called and tts is shutdown, returning back you use such destroyed tts which is wrong and can cause such behaviour.
You can move your code from onPause to onStop, and your init code to onStart. In onActivityResult set some class instance variable with data to speak inside onInit.
Related
I am using the default dictionary that comes with the pocketsphinx demo which is good for my purposes. When a user enters a phrase, the app starts a keyphrase listening but if the word is not found in the dictionary the app crashes. The app crashes onError() within a service. How is the error handling done? is there any way I can catch the error? Overall I would just like the service to call stopSelf() when an error happens so the main activity won't crash as well.
Errors:
ERROR: "kws_search.c", line 165: The word 'phonez' is missing in the dictionary
Fatal signal 11 (SIGSEGV) at 0x00000000 (code=1), thread 5389 (1994.wherephone)
Here is my service class:
public class WherePhoneService extends Service implements RecognitionListener {
private static String SettingStorage = "SavedData";
SharedPreferences settingData;
private SpeechRecognizer recognizer;
private String sInput;
private String sOutput;
private int seekVal;
private TextToSpeech reply;
private AsyncTask t;
public WherePhoneService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
makeText(getApplicationContext(), "onHandle start", Toast.LENGTH_SHORT).show();
getValues();
startTTS();
t = new AsyncTask<Void, Void, Exception>() {
#Override
protected Exception doInBackground(Void... params) {
try {
Assets assets = new Assets(WherePhoneService.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
} catch (IOException e) {
return e;
}
return null;
}
#Override
protected void onPostExecute(Exception result) {
if (result != null) {
//((TextView) findViewById(R.id.caption_text)).setText("Failed to init recognizer " + result);
} else {
switchSearch(sInput);
}
}
}.execute();
return Service.START_STICKY;
}
private void setupRecognizer(File assetsDir) throws IOException {
recognizer = defaultSetup()
.setAcousticModel(new File(assetsDir, "en-us-ptm"))
.setDictionary(new File(assetsDir, "cmudict-en-us.dict"))
// To disable logging of raw audio comment out this call (takes a lot of space on the device)
//.setRawLogDir(assetsDir)
// Threshold to tune for keyphrase to balance between false alarms and misses
.setKeywordThreshold(1e-45f)
// Use context-independent phonetic search, context-dependent is too slow for mobile
.setBoolean("-allphone_ci", true)
.getRecognizer();
recognizer.addListener(this);
// Create keyword-activation search.
recognizer.addKeyphraseSearch(sInput, sInput);
}
private void switchSearch(String searchName) {
recognizer.stop();
// If we are not spotting, start listening with timeout (10000 ms or 10 seconds).
if (searchName.equals(sInput))
recognizer.startListening(searchName);
else
recognizer.startListening(searchName, 10000);
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onEndOfSpeech() {
if (!recognizer.getSearchName().equals(sInput))
switchSearch(sInput);
}
#Override
public void onPartialResult(Hypothesis hypothesis) {
if (hypothesis == null)
return;
String text = hypothesis.getHypstr();
makeText(getApplicationContext(), "Partial", Toast.LENGTH_SHORT).show();
if (text.equals(sInput)) {
setVolume();
// Text to speech
reply.speak(sOutput, TextToSpeech.QUEUE_ADD, null);
switchSearch(sInput);
}
else {
makeText(getApplicationContext(), "Try again", Toast.LENGTH_SHORT).show();
switchSearch(sInput);
}
}
#Override
public void onResult(Hypothesis hypothesis) {
if (hypothesis != null) {
// restart listener and affirm that partial has past
makeText(getApplicationContext(), "end", Toast.LENGTH_SHORT).show();
//recognizer.startListening(sInput);
switchSearch(sInput);
}
}
public void onError(Exception e) {
e.printStackTrace(); // not all Android versions will print the stack trace automatically
Intent intent = new Intent ();
intent.setAction ("com.mydomain.SEND_LOG"); // see step 5.
intent.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK); // required when starting from Application
startActivity (intent);
stopSelf();
}
#Override
public void onTimeout() {
switchSearch(sInput);
}
public void startTTS() {
reply = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
reply.setLanguage(Locale.UK);
}
}
});
}
public void getValues() {
settingData = getBaseContext().getSharedPreferences(SettingStorage, 0);
sInput = settingData.getString("inputstring", "Where is my phone").toString().toLowerCase().replaceAll("[^\\w\\s]", "");
sOutput = settingData.getString("outputstring", "").toString().toLowerCase();
seekVal = settingData.getInt("seekval", 0);
}
public void setVolume() {
int seekValConvert = 0;
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int getMaxPhoneVol = audioManager.getStreamMaxVolume(audioManager.STREAM_MUSIC);
seekValConvert = ((seekVal * getMaxPhoneVol)/100);
audioManager.setStreamVolume(audioManager.STREAM_MUSIC, seekValConvert, 0);
}
#Override
public void onDestroy() {
super.onDestroy();
makeText(getApplicationContext(), "destroy", Toast.LENGTH_SHORT).show();
recognizer.cancel();
recognizer.shutdown();
t.cancel(true);
}
}
Crash is a bug in pocketsphinx-android. If you update to latest version from github, it should properly throw RuntimeException on any errors in methods addKeyphrase and setSearch.
I am using the following code. Its working fine except a problem that i have list of text to converted as speech. But its only converting last line as a speech. Here is my code where I am putting data in listview and trying to convert it into speech:
public class TextSpeech extends ListActivity implements
TextToSpeech.OnInitListener {
/** Called when the activity is first created. */
private TextToSpeech tts;
private TextView txtText;
private List<Message> mess;
List<String> titless;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.speach);
tts = new TextToSpeech(this, this);
BaseFeedParser parser = new BaseFeedParser();
mess = parser.parse();
titless = new ArrayList<String>(mess.size());
speakOut();
}
#SuppressLint("NewApi")
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#SuppressLint("NewApi")
#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 {
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
public void speakOut() {
for (Message msg : mess){
titless.add(msg.getTitle());
tts.speak(msg.getTitle(), TextToSpeech.QUEUE_FLUSH, null);
}
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(this, R.layout.row,titless);
this.setListAdapter(adapter);
}
}
You had used TextToSpeech.QUEUE_FLUSH just changed it to TextToSpeech.QUEUE_ADD .According to your requirement you want TTS to read one by one.
I am working on an Android navigation application for blind people. So naturally no use of displaying map on the screen. My code for now gets the path by building an url and then parsing the html document. I want to make this live i.e. i want to handle the case when he/she goes off the path or goes in the wrong direction, i want my app to alert him.
Is such a thing possible using a Google Maps feature? If possible please give details about that feature or if no such feature exists then is it possible to use existing feature and use it in some way to help solve the problem.
This is my present code:
public class GPSTracking extends Activity implements
TextToSpeech.OnInitListener
{
protected static final int RESULT_SPEECH_start = 1;
protected static final int RESULT_SPEECH_end = 2;
protected static final int RESTART_ALL = 3;
//total distance travelled till last turn
Float totalDistance;
//distance to be travelled from present point to the next point
Float obtainedDistance;
//upper button
Button btnShowLocation;
//bottom button
Button btnShowLocationNo;
//to narate what user should do.
TextToSpeech tts;
//used to get name of current location
Geocoder geocoder;
//used to find positioning feature
GPS gps;
//start and position of the journey
String startPosition=null, endPosition=null;
//strings containing the path.
String[] string = null;
//vibrate the mobile
Vibrator viberator;
//indexing the present value of string which contains the path
int i = 0;
//to maintain proper order of events
int steps=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//button on top
btnShowLocation = (Button) findViewById(R.id.trueButton);
//button on the lower side
btnShowLocationNo = (Button) findViewById(R.id.falseButton);
//initialising the text to speech
tts = new TextToSpeech(this, this);
//initialising the vibrator.
viberator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
//to know what the current location
btnShowLocation.setOnClickListener(new View.OnClickListener() {
//to avoid start of multiple threads
boolean mytaskStarted=false;
String str=null;
#Override
public void onClick(View v) {
if(steps==0){
//to make sure values are reset
totalDistance=(float)0;
obtainedDistance=(float)0;
mytaskStarted=false;
string=null;
str=null;
i=0;
//only ask for initial position if not set
if(startPosition == null){
speakOut("Please enter the start position");
//takes the input using speech to text
intentGenerator(RESULT_SPEECH_start);
}
else{
//to enter the destination
speakOut("press the button again");
steps=1;
}
}
else if(steps==1){
//to enter the destination
speakOut("Please enter the destination");
intentGenerator(RESULT_SPEECH_end);
}
else if(steps==2){
//for a impatient user
speakOut("please wait");
//to avoid start of many asynchronous task
if(!mytaskStarted){
mytaskStarted=true;
//asynchronous task to find the path to be followed
new GetPath().execute();
}
}
else if(steps==3){
if (string != null && i < string.length) {
if(gps!=null && gps.isGpsEnabled()){
speakOut(i + 1 + " " + string[i]);
if(i>0 && i<string.length-1 && (string[i]+" ").lastIndexOf(" m ")>-1){
str=(string[i]+" ").substring(0,(string[i]+" ").lastIndexOf(" m ")+3);
obtainedDistance=Float.parseFloat(str.substring(1+str.substring(0,str.substring(0,str.lastIndexOf(" ")).lastIndexOf(" ")).lastIndexOf(" "),str.substring(0,str.lastIndexOf(" ")).lastIndexOf(" ")));
//increment only when present distance greater than distance in present string so that one will know when to turn.
if(((totalDistance+obtainedDistance)-gps.getApprximateDistance())<10)
{
i++;
totalDistance=totalDistance+obtainedDistance;
}
}
else if(i>0 && i<string.length-1 && (string[i]+" ").lastIndexOf(" km ")>-1){
str=(string[i]+" ").substring(0,(string[i]+" ").lastIndexOf(" km ")+4);
obtainedDistance=Float.parseFloat(str.substring(1+str.substring(0,str.substring(0,str.lastIndexOf(" ")).lastIndexOf(" ")).lastIndexOf(" "),str.substring(0,str.lastIndexOf(" ")).lastIndexOf(" ")));
obtainedDistance*=1000;
//increment only when present distance greater than distance in present string so that one will know when to turn.
if(((totalDistance+obtainedDistance)-gps.getApprximateDistance())<10)
{
i++;
totalDistance=totalDistance+obtainedDistance;
}
}
else if(i==0 ){
i++;
}
}
else if(gps!=null){
gps.resetDistance();
gps.stopUsingGPS();
//if gps not working.
speakOut(i + 1 + " " + string[i]);
i++;
}
else{
speakOut(i + 1 + " " + string[i]);
i++;
}
} else if (string != null && i >= string.length) {
i = 0;
}
}
}
});
//to get present location
btnShowLocation.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if(gps==null){
gps = new GPS(AndroidGPSTrackingActivity.this);
}
if (gps.canGetLocation()) {
double longitude = gps.getLongitude();
double latitude = gps.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
//obtain the address of present location
List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
if(null!=listAddresses&&listAddresses.size()>0){
if (listAddresses.size() > 0) {
StringBuilder result = new StringBuilder();
for(int i = 0; i < listAddresses.size(); i++){
Address address = listAddresses.get(i);
int maxIndex = address.getMaxAddressLineIndex();
for (int x = 0; x <= maxIndex; x++ ){
if(address.getAddressLine(x)!=null){
result.append(address.getAddressLine(x));
result.append(",");
}
}
if(address.getLocality()!=null){
result.append(address.getLocality());
result.append("\n\n");
}
}
//if position accurate
if(gps.isGpsEnabled()){
speakOut(result.toString()+" is Your current location");
startPosition=result.toString();
Toast.makeText(
getApplicationContext(),startPosition,
Toast.LENGTH_LONG).show();
} else if(gps.isNetworkEnabled()){
speakOut(result.toString()+" is Your current approximate location. You have to give input of your present location on your own.");
Toast.makeText(
getApplicationContext(),result.toString(),
Toast.LENGTH_LONG).show();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
gps.showSettingsAlert();
startPosition=null;
speakOut(" please turn on gps");
}
return false;
}
});
//to know what the previous direction string
btnShowLocationNo.setOnClickListener(new View.OnClickListener() {
int j=0;
#Override
public void onClick(View arg0) {
if(string!=null && j<string.length){
speakOut(j + 1 + " " + string[j]);
j++;
}
else if(string!=null && j>=string.length){
j=0;
}
}
});
//to reset all values for fresh start
btnShowLocationNo.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
speakOut("Values reset");
steps=0;
string=null;
i=0;
startPosition=null;
gps.stopUsingGPS();
gps=null;
endPosition=null;
return false;
}
});
}
//function to handle he text obtained from speech to text.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
//set the start
case RESULT_SPEECH_start:
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Toast.makeText(getApplicationContext(), text.get(0),
Toast.LENGTH_SHORT).show();
startPosition = text.get(0);
steps=1;
//speakOut("please press button again");
}
else{
steps=0;
}
break;
//to set the end
case RESULT_SPEECH_end:
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Toast.makeText(getApplicationContext(), text.get(0),
Toast.LENGTH_SHORT).show();
endPosition = text.get(0);
steps=2;
}
else{
steps=1;
}
break;
}
}
//function to generate intent to take speech input
public void intentGenerator(int code) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, code);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
"Opps! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT).show();
speakOut("Opps! Your device doesn't support Speech to Text");
}
}
//mobile gives instruction.
private void speakOut(String text) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
while (tts.isSpeaking()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//asynchronous task to get the path. THIS IS USED TO AVOID OVERLOAD THE MAIN THRED AND AVOID FORCE CLOSE OF THE APPLICATION
private class GetPath extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
string=null;
String html="";
//forming url
URL net = new URL(("http://maps.google.com/maps?saddr="+startPosition+" &daddr= "+endPosition).replaceAll(" ","%20"));
URLConnection netConnection = null;
netConnection = net.openConnection();
//to take the input from google maps
BufferedReader in = null;
in = new BufferedReader(new InputStreamReader(netConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
html+=inputLine;
}
//jsoup parser to parse the document obtained from google maps
Document doc = Jsoup.parse(html);
//obtain necessary part of the document
Elements el = doc.getElementsByClass("dir-mrgnr");
//to remove html tags
String str = el.text();
str = str.replaceAll("[0-9]+[.] ", "\n");
string = str.split("\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//so that on press of button again mobile can read the directions to users
steps=3;
}
}
#Override
public void onDestroy() {
//shutdown
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
protected void onStart() {
gps = new GPS(AndroidGPSTrackingActivity.this);
super.onStart();
}
#Override
protected void onStop() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
if(gps!=null){
gps.stopUsingGPS();
}
super.onStop();
}
#Override
public void onInit(int status) {
//initialising the text to speech
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
btnShowLocation.setEnabled(true);
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
}
I am confused with a code which will speaks out the word from an edit text,The code i used is not speaking out but it getting the value,no of characters etc correctly.
The code i used is..
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);
System.out.println("Entered to the Activity");
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!
if (tts != null) {
System.out.println("Entered to OnDestroy");
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
System.out.println("Enterd init Function");
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.ENGLISH);
// tts.setPitch(5); // set pitch level
// tts.setSpeechRate(2); // set speech speed rate
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
btnSpeak.setEnabled(true);
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed");
}
}
private void speakOut() {
System.out.println("Entered Speakout");
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
It returning a message that languagge not supported..How can i rectify it
Try this it might help you.
I think in your device speech synthesizer is not installed so use these for this. If not installed it will redirect to google play to install this.
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = talker.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
} else {
btnSpeak.setEnabled(true);
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
Try out below code. It works fine for me i hope it will help you also.
public class TexttoSpeechActivity extends Activity implements OnClickListener,
OnInitListener {
private Button m_btnSpech;
private EditText m_etText;
// TTS object
private TextToSpeech m_tts;
// status check code
private final int m_data = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
m_btnSpech = (Button) findViewById(R.id.mbtnSpeak);
m_etText = (EditText) findViewById(R.id.metTextValues);
// listen for clicks
m_btnSpech.setOnClickListener(this);
// check for TTS data intent to check if a TTS engine is installed
Intent m_intent = new Intent();
m_intent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(m_intent, m_data);
}
// respond to button click.
#Override
public void onClick(View p_v) {
// get the text entered.
String m_word = m_etText.getText().toString();
speakWord(m_word);
}
/**
* Executed when a new TTS is instantiated. Some text is spoken via TTS
* here.
*
* #param p_word
* -contains the word entered into the edittext.
*/
private void speakWord(String p_word) {
// speak straight away
m_tts.speak(p_word, TextToSpeech.QUEUE_FLUSH, null);
}
/**
* This is the callback from the TTS engine check, if a TTS is installed we
* create a new TTS instance (which in turn calls onInit), if not then we
* will create an intent to go off and install a TTS engine
*
* #param p_requestCode
* int Request code returned from the check for TTS engine.
* #param p_resultCode
* int Result code returned from the check for TTS engine.
* #param p_data
* Intent Intent returned from the TTS check.
*/
#Override
protected void onActivityResult(int p_requestcode, int p_resultcode,
Intent p_data) {
if (p_requestcode == m_data) {
if (p_resultcode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// the user has the necessary data - create the TTS
m_tts = new TextToSpeech(this, this);
} else {
// no data - install it now
Intent m_intnt = new Intent();
m_intnt.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(m_intnt);
}
}
}
// setup TTS
#Override
public void onInit(int p_status) {
// check for successful instantiation
if (p_status == TextToSpeech.SUCCESS) {
if (m_tts.isLanguageAvailable(Locale.US) == TextToSpeech.LANG_AVAILABLE) {
m_tts.setLanguage(Locale.US);
Toast.makeText(this, "Text To Speech ", Toast.LENGTH_LONG)
.show();
}
Toast.makeText(TexttoSpeechActivity.this,
"Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
} else if (p_status == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...",
Toast.LENGTH_LONG).show();
}
}
/**
* Be kind, once you've finished with the TTS engine, shut it down so other
* applications can use it without us interfering with it.
*/
#Override
public void onDestroy() {
// Don't forget to shutdown!
if (m_tts != null) {
m_tts.stop();
m_tts.shutdown();
}
super.onDestroy();
}
}
Does anybody have idea why the TextToSpeech method I have here doesn't work anymore on Android 4.1?
On the sayIt() method it always returns Log.i(TAG, "Failure: TextToSpeech instance tts was not properly initialized");
public class SpeakSuperActivity extends Activity implements OnInitListener {
private final static String TAG = "TextToSpeech";
protected static final Locale defaultLocale = Locale.GERMAN;
private static int TTS_DATA_CHECK = 100;
protected TextToSpeech tts = null;
protected boolean ttsIsInit = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Use an Intent and startActivityForResult to check whether TTS data installed on the
// device. Result returned and acted on in method onActivityResult(int, int, Intent) below.
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, TTS_DATA_CHECK);
}
// protected void initTextToSpeech() {
// Log.d(TAG, "TTS initTextToSpeech() called");
// Intent intent = new Intent(Engine.ACTION_CHECK_TTS_DATA);
// startActivityForResult(intent, TTS_DATA_CHECK);
// }
protected void onActivityResultOld(int requestCode, int resultCode, Intent data) {
if (requestCode == TTS_DATA_CHECK) {
Log.d(TAG, "onActivityResult: TTS_DATA_CHECK fork reached");
if (resultCode == Engine.CHECK_VOICE_DATA_PASS) {
Log.d(TAG, "Data installed: Engine.CHECK_VOICE_DATA_PASS fork reached");
tts = new TextToSpeech(this, this);
// tts = new TextToSpeech(this, new OnInitListener() {
// public void onInit(int status) {
// if (status == TextToSpeech.SUCCESS) {
// Log.w(TAG, "TTS onInit() success :)");
// ttsIsInit = true;
// if (tts.isLanguageAvailable(Locale.UK) >= 0) {
// Log.d(TAG, "Local UK available");
// tts.setLanguage(Locale.UK);
// }
// if (tts.isLanguageAvailable(Locale.GERMAN) >= 0) {
// Log.d(TAG, "Local German available");
// tts.setLanguage(Locale.GERMAN);
// }
// tts.setPitch(0.8f);
// tts.setSpeechRate(1.1f);
// speak("Hallo Sprücheklopfer");
// } else if (status == TextToSpeech.ERROR) {
// Log.w(TAG, "TTS onInit() failed :(");
// }
// }
// });
} else {
Log.i(TAG, "TTS not installed yet, calling intent to install...");
Intent installVoice = new Intent(Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installVoice);
}
}
}
// Create the TTS instance if TextToSpeech language data are installed on device. If not
// installed, attempt to install it on the device.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TTS_DATA_CHECK) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// Success, so create the TTS instance. But can't use it to speak until
// the onInit(status) callback defined below runs, indicating initialization.
Log.i(TAG, "Success, let's talk");
// XXX: NOTE: it is REALLY important to use new TextToSpeech(getApplicationContext(), this) instead of new TextToSpeech(this, this)!
tts = new TextToSpeech(getApplicationContext(), this);
// // Use static Locales method to list available locales on device
// Locale locales [] = Locale.getAvailableLocales();
// Log.i(TAG,"Locales Available on Device:");
// for(int i=0; i<locales.length; i++){
// String temp = "Locale "+i+": "+locales[i]+" Language="
// +locales[i].getDisplayLanguage();
// if(locales[i].getDisplayCountry() != "") {
// temp += " Country="+locales[i].getDisplayCountry();
// }
// Log.i(TAG, temp);
// }
} else {
// missing data, so install it on the device
Log.i(TAG, "Missing Data; Install it");
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
ttsIsInit = true;
// Set to a language locale after checking availability
Log.i(TAG, "defaultLocaleAvailable=" + tts.isLanguageAvailable(defaultLocale));
tts.setLanguage(defaultLocale);
// Examples of voice controls. Set to defaults of 1.0.
tts.setPitch(1.0F);
tts.setSpeechRate(1.0F);
// Issue a greeting and instructions in the default language
// speakGreeting(defaultLocale.getDisplayLanguage());
// sayIt("Hallo Sprücheklopfer", true);
} else {
ttsIsInit = false;
Log.i(TAG, "Failure: TextToSpeech instance tts was not properly initialized");
}
}
// protected void speak(String text) {
// Log.d(TAG, "TTS sould say: " + text);
// if (tts != null && ttsIsInit) {
// tts.speak(text, TextToSpeech.QUEUE_ADD, null);
// } else {
// Log.w(TAG, "TTS not initialised or null");
// }
// }
// Method to speak a string. The boolean flushQ determines whether the text is
// appended to the queue (if false), or if the queue is flushed first (if true).
public void sayIt(String text, boolean flushQ) {
if (tts != null && ttsIsInit) {
if (flushQ) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
} else {
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
} else {
Log.i(TAG, "Failure: TextToSpeech instance tts was not properly initialized");
}
}
// Release TTS resources when finished
#Override
protected void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
ttsIsInit = false;
}
super.onDestroy();
}
public void onInitOld(int status) {
Log.i(TAG, "TTS onInit() status :" + status);
if (status == TextToSpeech.SUCCESS) {
Log.w(TAG, "TTS onInit() success :)");
ttsIsInit = true;
if (tts.isLanguageAvailable(Locale.UK) >= 0) {
Log.d(TAG, "Local UK available");
tts.setLanguage(Locale.UK);
}
if (tts.isLanguageAvailable(Locale.GERMAN) >= 0) {
Log.d(TAG, "Local German available");
tts.setLanguage(Locale.GERMAN);
}
tts.setPitch(0.8f);
tts.setSpeechRate(1.1f);
sayIt("Hallo Sprücheklopfer", true);
} else if (status == TextToSpeech.ERROR) {
Log.w(TAG, "TTS onInit() failed :(");
} else {
Log.w(TAG, "TTS onInit() unknown status :" + status);
}
}
}