TextToSpeech - Android - android

I'm working on a simple game. The idea of the first round is that, there are 26 buttons (images) on the first activity - english alphabet and I want to make it pronounce on button click. For example, when I press "a" button, it must say "a". How can I get the ID of each button, then string of it and give it to speak() method as a parameter? THANKS IN ADVANCE !
Code is here:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import java.util.Locale;
import java.util.Random;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
public class FirstActivity extends Activity {
/** Called when the activity is first created. */
TextToSpeech ttx;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstact);
ttx = new TextToSpeech(
FirstActivity.this,
new TextToSpeech.OnInitListener() {
public void onInit(int status) {
// TODO Auto-generated method stub
if(status !=TextToSpeech.ERROR){
ttx.setLanguage(Locale.US);
}
}
});
TableLayout table = (TableLayout) findViewById(R.id.table);
String alphabet = "abcdefghijqlmnopqrstuvwxyz";
int pos = 0;
for (int i = 0; i < 7; i++) {
TableRow row = new TableRow(this);
for (int j = 0; j < 4; j++) {
if (pos == 26) {
break;
}
Button but = new Button(this);
/*but.setOnClickListener(btnListener);*/
but.setText(Character.toString(alphabet.charAt(pos++)));
but.setHeight(80);
but.setWidth(70);
but.setBackgroundResource(R.drawable.burti);
row.addView(but);
but.setId(pos);
but.setOnClickListener((OnClickListener) this);
table.addView(row);
}}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
if(ttx != null){
ttx.stop();
ttx.shutdown();
}
super.onPause();
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
String pressed = but.getText().toString(); //error here....
ttx.speak(pressed, TextToSpeech.QUEUE_FLUSH, null);
}
}

I made a working example: http://frank.anemaet.nl/android/TalkingButtons.zip
Here is a snippet of the working code:
for (int i = 0; i < alphabet.length(); i++)
{
TableRow row = new TableRow(this);
Button but;
but = new Button(this);
but.setText(Character.toString(alphabet.charAt(i)));
but.setHeight(button_width);
but.setWidth(button_height);
but.setId(i);
but.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
performClick(v);
}
});
row.addView(but);
table.addView(row);
}
...
public void performClick(View arg0){
Button tv = (Button)findViewById(arg0.getId());
String pressed = tv.getText().toString();
ttx.speak(pressed, TextToSpeech.QUEUE_FLUSH, null);
}

Your onInit() method has to do more, like handle when the user does not have the language data installed.
See this code for a helper class.

Related

string array changing onClick

I wish to have questions that change to the next question in the sequence onClick but I'm having trouble creating the array of questions and writing the onClick code for that portion.
*Too add more context to the app it will be a questionaire app with a question above an editText field and the users inputs will show up in its respective box at the top of the screen.
package com.example.greg;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class menu extends Activity {
Button mButton;
EditText mEdit;
int questionNumber = 0;
String [] questions;
int numberOfQuestions = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button)findViewById(R.id.button);
mEdit = (EditText)findViewById(R.id.userAnswereditText);
questions=new String[numberOfQuestions];
questions[0]="This is first question?";
questions[1]="This is second question?";
final TextView [] myTexts = new TextView[2];
myTexts[0]=(TextView)findViewById(R.id.varATextView);
myTexts[1]=(TextView)findViewById(R.id.varBTextView);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
myTexts[questionNumber].setText(mEdit.getText().toString());
mEdit.setText(null);
questionNumber++;
if(questionNumber < numberOfQuestions)
questionTextViewHolder.setText(questions[questionNumber]);
else
Toast.makeText(menu.this,"No more questions!",Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}

Closing Android Game After 5 Seconds

I'm tring to build an simple android game.
Users answer the questions, when the answer is correct, it is continue..
I want to add time control for each answer.
I tried to add handler function, but I didn't.
My Code;
import java.util.Collections;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class EasyGameActivity extends Activity {
public int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_easygame);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
finishScreen();
}
}, 5000);
startGame();
}
private void startGame() {
// TODO Auto-generated method stub
Button b1 = (Button)findViewById(R.id.answer_one);
Button b2 = (Button)findViewById(R.id.answer_two);
Button b3 = (Button)findViewById(R.id.answer_three);
Button b4 = (Button)findViewById(R.id.answer_four);
Random number = new Random();
int first = number.nextInt(100)+1;
int second = number.nextInt(100)+1;
int answer = first + second;
int rnd1 = answer + 1;
int rnd2 = answer + 2;
int rnd3 = answer - 1;
final String a = Integer.toString(answer);
String b = Integer.toString(rnd1);
String c = Integer.toString(rnd2);
String d = Integer.toString(rnd3);
((TextView) findViewById(R.id.display)).setText(Integer.toString(first) + '+' + Integer.toString(second));
List<Button> buttons = Arrays.asList(b1, b2, b3, b4);
List<String> texts = Arrays.asList(a, b, c, d);
Collections.shuffle(texts);
int i = 0;
OnClickListener onClick = new OnClickListener() {
public void onClick(View view) {
Button button = (Button) view;
String value = (String) button.getText();
if(value == a) {
checkTrue();
} else {
finishScreen();
}
}
};
for(Button button : buttons) {
button.setText(texts.get(i++));
button.setOnClickListener(onClick);
}
}
private void checkTrue() {
score++;
((TextView) findViewById(R.id.score)).setText(Integer.toString(score));
startGame();
}
private void finishScreen() {
score = 0;
startActivity (new Intent("com.bsinternet.mathfast.RESTARTGAMESCREEN"));
finish();
}
}
How can I add time control. Thanks.
This bit of code doesn't look right
if(value == a) {
checkTrue();
} else {
finishScreen();
}
You should be using equals() to check for String equality. At the moment you are checking only object equality, which will evaluate to False, and the code will never call checkTrue().
Do this instead:
if(value.equals(a) {
checkTrue();
} else {
finishScreen();
}

SpellChecker Showing Error in Android?

I am trying to run the Android SpellChecker With The EditText but it is not running displaying some errors as follows:
My Activity is As Follows:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.textservice.SentenceSuggestionsInfo;
import android.view.textservice.SpellCheckerSession;
import android.view.textservice.SpellCheckerSession.SpellCheckerSessionListener;
import android.view.textservice.SuggestionsInfo;
import android.view.textservice.TextInfo;
import android.view.textservice.TextServicesManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class HelloSpellCheckerActivity extends Activity implements SpellCheckerSessionListener {
private static final int NOT_A_LENGTH = -1;
private TextView mMainView;
private SpellCheckerSession mScs;
private EditText editText1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mMainView = (TextView)findViewById(R.id.main);
editText1 = (EditText)findViewById(R.id.editText1);
}
#Override
public void onResume() {
super.onResume();
final TextServicesManager tsm = (TextServicesManager) getSystemService(
Context.TEXT_SERVICES_MANAGER_SERVICE);
mScs = tsm.newSpellCheckerSession(null, null, this, true);
}
#Override
public void onPause() {
super.onPause();
if (mScs != null) {
mScs.close();
}
}
public void go(View view){
Toast.makeText(getApplicationContext(), editText1.getText().toString(),
Toast.LENGTH_SHORT).show();
mScs.getSuggestions(new TextInfo(editText1.getText().toString()), 3);
}
#Override
public void onGetSuggestions(final SuggestionsInfo[] arg0) {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < arg0.length; ++i) {
// Returned suggestions are contained in SuggestionsInfo
final int len = arg0[i].getSuggestionsCount();
sb.append('\n');
for (int j = 0; j < len; ++j) {
sb.append("," + arg0[i].getSuggestionAt(j));
}
sb.append(" (" + len + ")");
}
runOnUiThread(new Runnable() {
public void run() {
mMainView.append(sb.toString());
}
});
}
#Override
public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] arg0) {
// TODO Auto-generated method stub
}
}
I am uploading an image of the error. Please have a look and let me know why this error is occuring:
Your manifest has minSdkVersion as 8, which won't work.
You will have to change your minSdkVersion to 14 in manifest file.
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="18" />
As SpellCheckerSessionListener was added in API level 14, your project is showing errors.
Hope this helps.

Android Switching Activities Black Screen

I'm trying to start another activity in my main activity using this method:
public void switchToRead(){// Switches to the reading view which displays the text that the tts engine reads off.
Intent intent = new Intent(getApplicationContext(),ReadOut.class);
intent.putExtra("response", res);
startActivity(intent);
}
This starts the following class:
package com.example.webview;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ReadOut extends Activity implements TextToSpeech.OnInitListener, OnClickListener {
boolean paused = false;
String leftToRead = null;
String res = null;
TextToSpeech tts;
protected void onPreExecute()
{
System.out.println("Pre-execute");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.read_out);
Intent intent = getIntent();
res = intent.getExtras().getString("response");
TextView textv = (TextView) findViewById(R.id.textView1);
textv.setText(res);
textv.setMovementMethod(new ScrollingMovementMethod());
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
textv.setHeight((int)(display.getHeight()*0.76));
System.out.println("START");
tts = new TextToSpeech(this, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
public String speakFull(String text){
System.out.println("Speaking: " + text);
System.out.println("Speaking");
String[] sentences = text.split("\n|\\.(?!\\d)|(?<!\\d)\\."); // Regex that splits the body of text into the sentences of that body which are stored in a String array.
for(int i = 0; i < sentences.length; i++){
if(!tts.isSpeaking() && !paused){
System.out.println("Speaking: " + i);
tts.speak(sentences[i], TextToSpeech.QUEUE_FLUSH, null);
}else if(paused){
System.out.println("Paused");
String paused = "";
int k = 0;
if(i != 0){
k = i-1;
}
leftToRead = null;
for(int j = k; j < sentences.length; j++){
leftToRead += sentences[j];
}
return leftToRead;
}else{
i--;
System.out.println("Sleeping");
System.out.println("Speaking : " + tts.isSpeaking());
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
if(i == sentences.length - 1){
return "Message 001: Complete";
}
}
return null;
}
#Override
public void onInit(int arg0) {
System.out.println("speakFull");
leftToRead = speakFull(res);
}
public void clickPause(View v){
if(paused){
paused = false;
Button b = (Button) findViewById(R.id.button1);
b.setText("Play");
}else{
paused = true;
Button b = (Button) findViewById(R.id.button1);
b.setText("Pause");
if(leftToRead == null){
leftToRead = speakFull(res);
}else{
leftToRead = speakFull(leftToRead);
}
}
}
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}
After the ReadOut class is started one of a couple things can happen,
either the screen turns black, the text to speech begins reading, and the app is telling me it's not responding, OR it shows me the view for ReadOut, reads in text to speech, and then tells me it's not responding.
I'm really confused as to why this is happening, and any insight would be appreciated.
I don't know anything about using TTS but I can tell you that this line is probably causing a problem
Thread.sleep(1000);
It appears you are calling it on the UI Thread which isn't a good idea. You need to use a background Thread and update it with something like runOnUiThread() or AsyncTask or you could use a Handler.

I can not pass the parameter i to the button[i]

I am trying to play a sound on button click and I am trying to make it call the .start() function only but the problem is I set the i parameter in the onclick function and so it does not pass the i to the onclicklistner function any ideas how to fix that ??
here is my code
package com.example.buttonsdemo;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnClickListener{
//Creating Sound arrays
int i=0;
MediaPlayer[] mediaplayer = new MediaPlayer[120];
Button button[] = new Button [120];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialize the mediaplayer
for(int z=0;z<120;z++)
{
mediaplayer[z]=null;
}
//Initialize Button Array
for(int x=0;x<120;x++)
{
button[x]=new Button(this);
button[x].setOnClickListener(this);
}
//Creating Media player array
mediaplayer[0]= MediaPlayer.create(this,R.raw.akali);
mediaplayer[1]= MediaPlayer.create(this,R.raw.alistar);
button[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.akali:
i=0;
break;
case R.id.alistar:
i=1;
break;
}
mediaplayer[i].start();
}
} );
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Inside your Listener, you want to use a variable which is declared inside your Listener.
You are trying to use a variable (i) which is declared in code which is not run when the Listener is run.
new View.OnClickListener() {
#Override
public void onClick(View v) {
int idx;
switch(v.getId()) {
case R.id.akali:
idx=0;
break;
case R.id.alistar:
idx=1;
break;
}
mediaplayer[idx].start();
}
}
Or invoke the respective start() method right in the case.
Dump the 'i' declared. Replace method with this (the "Button theButton" needs to stay 'final').
for(int z=0;z<120;z++)
{
final Button theButton = button[z];
theButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
// do what you want.
}
});
}
I believe your onCreate should be created like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialize the mediaplayer
for(int z=0;z<120;z++)
{
mediaplayer[z]=null;
}
mediaplayer[0]= MediaPlayer.create(this,R.raw.akali);
mediaplayer[1]= MediaPlayer.create(this,R.raw.alistar);
//Initialize Button Array
for( x=0;x<120;x++)
{
button[x]=new Button(this);
button[x].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaplayer[x].start();
}
} );
}
}
So basically you just need to make several button on the fly which produces different sound when clicked. Try this code:
Button myButton[] = new Button[100];
MediaPlayer mySound = new MediaPlayer();
for (int i=0; i<100; i++) {
myButton[i] = new Button(this);
myButton[i].setId(i+1);
myButton[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Resources res = context.getResources();
int soundId = res.getIdentifier("sound" + v.getId(), "raw", context.getPackageName());
mySound.create(getApplicationContext(), soundId);
mySound.start();
}
});
}

Categories

Resources