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);
}
}
}
Related
I am developing an app in which I want to use transliteration from Hindi to English via speech input. for that, I am using google STT API. Everything works when my voice input is short, but when I give long voice input, Dialog gets stuck at "Try Saying Something..." and I don't get results a well.
This is my Main Activity:-
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// Record Button
AppCompatButton RecordBtn;
// TextView to show Original and recognized Text
TextView Original,result;
// Request Code for STT
private final int SST_REQUEST_CODE = 101;
// Conversion Table Object...
ConversionTable conversionTable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Original = findViewById(R.id.Original_Text);
RecordBtn = findViewById(R.id.RecordBtn);
result = findViewById(R.id.Recognized_Text);
RecordBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.RecordBtn:
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// For 30 Sec it will Record...
intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 30);
// Use Off line Recognition Engine only...
intent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, false);
// Use Hindi Speech Recognition Model...
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "hi-IN");
try {
startActivityForResult(intent, SST_REQUEST_CODE);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.error),
Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case SST_REQUEST_CODE:
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> getResult = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Original.setText(getResult.get(0));
conversionTable = new ConversionTable();
String Transformed_String = conversionTable.transform(getResult.get(0));
result.setText(Transformed_String);
}
break;
}
}
}
My ConversationTable.class :-
package android.example.com.conversion;
import android.util.Log;
import java.util.ArrayList;
import java.util.Hashtable;
public class ConversionTable
{
private String TAG = "Conversation Table";
private Hashtable<String,String> unicode;
private void populateHashTable()
{
unicode = new Hashtable<>();
// unicode
unicode.put("\u0901","rha"); // anunAsika - cchandra bindu, using ~ to // *
unicode.put("\u0902","n"); // anusvara
unicode.put("\u0903","ah"); // visarga
unicode.put("\u0940","ee");
unicode.put("\u0941","u");
unicode.put("\u0942","oo");
unicode.put("\u0943","rhi");
unicode.put("\u0944","rhee"); // * = Doubtful Case
unicode.put("\u0945","e");
unicode.put("\u0946","e");
unicode.put("\u0947","e");
unicode.put("\u0948","ai");
unicode.put("\u0949","o");
unicode.put("\u094a","o");
unicode.put("\u094b","o");
unicode.put("\u094c","au");
unicode.put("\u094d","");
unicode.put("\u0950","om");
unicode.put("\u0958","k");
unicode.put("\u0959","kh");
unicode.put("\u095a","gh");
unicode.put("\u095b","z");
unicode.put("\u095c","dh"); // *
unicode.put("\u095d","rh");
unicode.put("\u095e","f");
unicode.put("\u095f","y");
unicode.put("\u0960","ri");
unicode.put("\u0961","lri");
unicode.put("\u0962","lr"); // *
unicode.put("\u0963","lree"); // *
unicode.put("\u093E","aa");
unicode.put("\u093F","i");
// Vowels and Consonants...
unicode.put("\u0905","a");
unicode.put("\u0906","a");
unicode.put("\u0907","i");
unicode.put("\u0908","ee");
unicode.put("\u0909","u");
unicode.put("\u090a","oo");
unicode.put("\u090b","ri");
unicode.put("\u090c","lri"); // *
unicode.put("\u090d","e"); // *
unicode.put("\u090e","e"); // *
unicode.put("\u090f","e");
unicode.put("\u0910","ai");
unicode.put("\u0911","o");
unicode.put("\u0912","o");
unicode.put("\u0913","o");
unicode.put("\u0914","au");
unicode.put("\u0915","k");
unicode.put("\u0916","kh");
unicode.put("\u0917","g");
unicode.put("\u0918","gh");
unicode.put("\u0919","ng");
unicode.put("\u091a","ch");
unicode.put("\u091b","chh");
unicode.put("\u091c","j");
unicode.put("\u091d","jh");
unicode.put("\u091e","ny");
unicode.put("\u091f","t"); // Ta as in Tom
unicode.put("\u0920","th");
unicode.put("\u0921","d"); // Da as in David
unicode.put("\u0922","dh");
unicode.put("\u0923","n");
unicode.put("\u0924","t"); // ta as in tamasha
unicode.put("\u0925","th"); // tha as in thanks
unicode.put("\u0926","d"); // da as in darvaaza
unicode.put("\u0927","dh"); // dha as in dhanusha
unicode.put("\u0928","n");
unicode.put("\u0929","nn");
unicode.put("\u092a","p");
unicode.put("\u092b","ph");
unicode.put("\u092c","b");
unicode.put("\u092d","bh");
unicode.put("\u092e","m");
unicode.put("\u092f","y");
unicode.put("\u0930","r");
unicode.put("\u0931","rr");
unicode.put("\u0932","l");
unicode.put("\u0933","ll"); // the Marathi and Vedic 'L'
unicode.put("\u0934","lll"); // the Marathi and Vedic 'L'
unicode.put("\u0935","v");
unicode.put("\u0936","sh");
unicode.put("\u0937","ss");
unicode.put("\u0938","s");
unicode.put("\u0939","h");
// represent it\
// unicode.put("\u093c","'"); // avagraha using "'"
// unicode.put("\u093d","'"); // avagraha using "'"
unicode.put("\u0969","3"); // 3 equals to pluta
unicode.put("\u014F","Z");// Z equals to upadhamaniya
unicode.put("\u0CF1","V");// V equals to jihvamuliya....but what character have u settled for jihvamuliya
/* unicode.put("\u0950","Ω"); // aum
unicode.put("\u0958","κ"); // Urdu qaif
unicode.put("\u0959","Κ"); //Urdu qhe
unicode.put("\u095A","γ"); // Urdu gain
unicode.put("\u095B","ζ"); //Urdu zal, ze, zoe
unicode.put("\u095E","φ"); // Urdu f
unicode.put("\u095C","δ"); // Hindi 'dh' as in padh
unicode.put("\u095D","Δ"); // hindi dhh*/
unicode.put("\u0926\u093C","τ"); // Urdu dwad
unicode.put("\u0924\u093C","θ"); // Urdu toe
unicode.put("\u0938\u093C","σ"); // Urdu swad, se
}
ConversionTable()
{
populateHashTable();
}
public String transform(String s1)
{
StringBuilder transformed = new StringBuilder();
int strLen = s1.length();
ArrayList<String> shabda = new ArrayList<>();
String lastEntry = "";
for (int i = 0; i < strLen; i++)
{
char c = s1.charAt(i);
String varna = String.valueOf(c);
Log.d(TAG, "transform: " + varna + "\n");
String halant = "0x0951";
if (VowelUtil.isConsonant(varna))
{
Log.d(TAG, "transform: " + unicode.get(varna));
shabda.add(unicode.get(varna));
shabda.add(halant); //halant
lastEntry = halant;
}
else if (VowelUtil.isVowel(varna))
{
Log.d(TAG, "transform: " + "Vowel Detected...");
if (halant.equals(lastEntry))
{
if (varna.equals("a"))
{
shabda.set(shabda.size() - 1,"");
}
else
{
shabda.set(shabda.size() - 1, unicode.get(varna));
}
}
else
{
shabda.add(unicode.get(varna));
}
lastEntry = unicode.get(varna);
} // end of else if is-Vowel
else if (unicode.containsKey(varna))
{
shabda.add(unicode.get(varna));
lastEntry = unicode.get(varna);
}
else
{
shabda.add(varna);
lastEntry = varna;
}
} // end of for
for (String string: shabda)
{
transformed.append(string);
}
//Discard the shabda array
shabda = null;
return transformed.toString(); // return transformed;
}
}
My ViewUtil Class:-
package android.example.com.conversion;
public class VowelUtil {
protected static boolean isVowel(String strVowel) {
// Log.logInfo("came in is_Vowel: Checking whether string is a Vowel");
return strVowel.equals("a") || strVowel.equals("aa") || strVowel.equals("i") || strVowel.equals("ee") ||
strVowel.equals("u") || strVowel.equals("oo") || strVowel.equals("ri") || strVowel.equals("lri") || strVowel.equals("e")
|| strVowel.equals("ai") || strVowel.equals("o") || strVowel.equals("au") || strVowel.equals("om");
}
protected static boolean isConsonant(String strConsonant) {
// Log.logInfo("came in is_consonant: Checking whether string is a
// consonant");
return strConsonant.equals("k") || strConsonant.equals("kh") || strConsonant.equals("g")
|| strConsonant.equals("gh") || strConsonant.equals("ng") || strConsonant.equals("ch") || strConsonant.equals("chh") || strConsonant.equals("j")
|| strConsonant.equals("jh") || strConsonant.equals("ny") || strConsonant.equals("t") || strConsonant.equals("th") ||
strConsonant.equals("d") || strConsonant.equals("dh") || strConsonant.equals("n") || strConsonant.equals("nn") || strConsonant.equals("p") ||
strConsonant.equals("ph") || strConsonant.equals("b") || strConsonant.equals("bh") || strConsonant.equals("m") || strConsonant.equals("y") ||
strConsonant.equals("r") || strConsonant.equals("rr") || strConsonant.equals("l") || strConsonant.equals("ll") || strConsonant.equals("lll") ||
strConsonant.equals("v") || strConsonant.equals("sh") || strConsonant.equals("ss") || strConsonant.equals("s") || strConsonant.equals("h") ||
strConsonant.equals("3") || strConsonant.equals("z") || strConsonant.equals("v") || strConsonant.equals("Ω") ||
strConsonant.equals("κ") || strConsonant.equals("K") || strConsonant.equals("γ") || strConsonant.equals("ζ") || strConsonant.equals("φ") ||
strConsonant.equals("δ") || strConsonant.equals("Δ") || strConsonant.equals("τ") || strConsonant.equals("θ") || strConsonant.equals("σ");
}
}
Outputs :-
for Short voice input :-
for Long voice Input, it stuck and can't get the result:-
The Problem is in Google's Implementation. I was facing the same type of difficulty and tried all the things, but did not work on anything.
So, i went on another way to solve this problem and the solution is implementing listeners by yourself. Here is my code for the same, it never popup the Inbuilt dialog (You can implement your custom dialog), but it works like charm.
Here is how you can do it :
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// Record Button
AppCompatButton RecordBtn;
// TextView to show Original
TextView Original;
// SpeechRecognizer Object...
private SpeechRecognizer speechRecognizer;
// For TAG
private String TAG = getClass().getName();
// RecognizerIntent
private Intent recognizerIntent;
// Request Code for Permission
private static final int REQUEST_CODE_RECORD_AUDIO = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Original = findViewById(R.id.Original_Text);
RecordBtn = findViewById(R.id.RecordBtn);
recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, R.string.record);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
recognizerIntent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, false);
}
// For 30 Sec it will Record...
recognizerIntent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 30);
// Use Hindi Speech Recognition Model...
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "hi-IN");
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
// Permission Dialog
Askpermission();
RecordBtn.setOnClickListener(this);
}
private void Askpermission() {
// No explanation needed; request the permission
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECORD_AUDIO},
REQUEST_CODE_RECORD_AUDIO);
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_RECORD_AUDIO: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Operation();
} else {
Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.RecordBtn:
Log.d(TAG, "onClick: ");
if (checkPermission()) {
if (IsAvailable(this)) {
Log.d(TAG, "Speech Recognition Service Available...");
speechRecognizer.startListening(recognizerIntent);
} else {
Toast.makeText(this, "Speech Recognition Service not Available on your device...",
Toast.LENGTH_SHORT)
.show();
}
} else {
Askpermission();
}
break;
}
}
// Check if Speech recognition Service is Available on the Smartphone...
private boolean IsAvailable(Context context) {
return SpeechRecognizer.isRecognitionAvailable(context);
}
#Override
protected void onDestroy() {
super.onDestroy();
speechRecognizer.destroy();
}
// Check Audio Permission
private boolean checkPermission() {
return ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) ==
PackageManager.PERMISSION_GRANTED;
}
// Start Operation
private void Operation() {
speechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
Log.d(TAG, "Audio Service is connected to Servers....");
Log.d(TAG, "You can now start your speech...");
}
#Override
public void onBeginningOfSpeech() {
Log.d(TAG, "User has started speech...");
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
Log.d(TAG, "User has Finished... speech...");
}
#Override
public void onError(int error) {
Log.d(TAG, "onError: " + error);
switch (error){
case SpeechRecognizer.ERROR_AUDIO:
Toast.makeText(MainActivity.this, "Error Recording Audio...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_CLIENT:
Toast.makeText(MainActivity.this, "Client Side Error...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
Toast.makeText(MainActivity.this, "Insufficient permissions...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_NETWORK:
Toast.makeText(MainActivity.this, "Network Related Error...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_NO_MATCH:
Toast.makeText(MainActivity.this, "Please Installed Offline Hindi " +
"Language Data...", Toast.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
Toast.makeText(MainActivity.this, "Recognition Busy...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_SERVER:
Toast.makeText(MainActivity.this, "Please Installed Offline Hindi " +
"Language Data...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
Toast.makeText(MainActivity.this, "Speech Timeout...", Toast
.LENGTH_SHORT).show();
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
Toast.makeText(MainActivity.this, "Network Timeout Error...", Toast
.LENGTH_SHORT).show();
}
}
#Override
public void onResults(Bundle results) {
ArrayList<String> Results = results.getStringArrayList(SpeechRecognizer
.RESULTS_RECOGNITION);
if (Results != null) {
Original.setText(Results.get(0));
}
}
#Override
public void onPartialResults(Bundle partialResults) {
}
#Override
public void onEvent(int eventType, Bundle params) {
}
});
}
}
I am creating a game using the API of Google Play Games. I have read the documentation on the leaderboards. I have used the same code to update the user's score, but it always returns the code RESULT_RECONNECT_REQUIRED. I've used the logcat to display the results of the call:
E/GameProgress: Result score CgkIoY-5lt0DEAIQEA: ScoreSubmissionData{PlayerId=128090785697, StatusCode=2, TimesSpan=DAILY, Result=null, TimesSpan=WEEKLY, Result=null, TimesSpan=ALL_TIME, Result=null}
Here is the code:
public class GameActivity extends AppCompatActivity {
private GameHelper mHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
...
mHelper = new GameHelper(this, 1);
mHelper.enableDebugLog(true);
mHelper.setup(new GameHelper.GameHelperListener() {
#Override
public void onSignInFailed() {
Log.e(TAG, "Sign in failed");
}
#Override
public void onSignInSucceeded() {
Log.e(TAG, "Sign in Succeded");
addScores(GameId.LEADERBOARDS.TEN_THOUSAND);
}
});
}
private void addScores(String leaderBoard) {
PendingResult<Leaderboards.SubmitScoreResult> result = Games.Leaderboards.submitScoreImmediate(mGoogleApiClient, leaderBoard, 5);
result.setResultCallback(new ResultCallback<Leaderboards.SubmitScoreResult>() {
#Override
public void onResult(#NonNull Leaderboards.SubmitScoreResult submitScoreResult) {
Log.e(TAG, "Result score " + leaderBoard + ": " + submitScoreResult.getScoreData().toString());
}
});
}
}
GameHelperClass:
public class GameHelper implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
static final String TAG = "GameHelper";
public interface GameHelperListener {
void onSignInFailed();
void onSignInSucceeded();
}
private boolean mSetupDone = false;
private boolean mConnecting = false;
boolean mExpectingResolution = false;
boolean mSignInCancelled = false;
Activity mActivity = null;
Context mAppContext = null;
public final static int RC_RESOLVE = 9001;
final static int RC_UNUSED = 9002;
GoogleApiClient.Builder mGoogleApiClientBuilder = null;
GamesOptions mGamesApiOptions = GamesOptions.builder().build();
PlusOptions mPlusApiOptions = null;
GoogleApiClient mGoogleApiClient = null;
// Client request flags
public final static int CLIENT_NONE = 0x00;
public final static int CLIENT_GAMES = 0x01;
public final static int CLIENT_PLUS = 0x02;
public final static int CLIENT_SNAPSHOT = 0x08;
public final static int CLIENT_ALL = CLIENT_GAMES | CLIENT_PLUS
| CLIENT_SNAPSHOT;
int mRequestedClients = CLIENT_NONE;
boolean mConnectOnStart = true;
boolean mUserInitiatedSignIn = false;
ConnectionResult mConnectionResult = null;
SignInFailureReason mSignInFailureReason = null;
boolean mShowErrorDialogs = true;
boolean mDebugLog = false;
Handler mHandler;
Invitation mInvitation;
TurnBasedMatch mTurnBasedMatch;
ArrayList<GameRequest> mRequests;
// Listener
GameHelperListener mListener = null;
static final int DEFAULT_MAX_SIGN_IN_ATTEMPTS = 3;
int mMaxAutoSignInAttempts = DEFAULT_MAX_SIGN_IN_ATTEMPTS;
private GameErrorHandler mGameErrorHandler;
public GameHelper(Activity activity, int clientsToUse) {
mActivity = activity;
mAppContext = activity.getApplicationContext();
mRequestedClients = clientsToUse;
mHandler = new Handler();
}
public void setMaxAutoSignInAttempts(int max) {
mMaxAutoSignInAttempts = max;
}
public void setGameErrorHandler(GameErrorHandler mGameErrorHandler) {
this.mGameErrorHandler = mGameErrorHandler;
}
void assertConfigured(String operation) {
if (!mSetupDone) {
String error = "GameHelper error: Operation attempted without setup: "
+ operation
+ ". The setup() method must be called before attempting any other operation.";
logError(error);
throw new IllegalStateException(error);
}
}
private void doApiOptionsPreCheck() {
if (mGoogleApiClientBuilder != null) {
String error = "GameHelper: you cannot call set*ApiOptions after the client "
+ "builder has been created. Call it before calling createApiClientBuilder() "
+ "or setup().";
logError(error);
throw new IllegalStateException(error);
}
}
public void setGamesApiOptions(GamesOptions options) {
doApiOptionsPreCheck();
mGamesApiOptions = options;
}
public void setPlusApiOptions(PlusOptions options) {
doApiOptionsPreCheck();
mPlusApiOptions = options;
}
public GoogleApiClient.Builder createApiClientBuilder() {
if (mSetupDone) {
String error = "GameHelper: you called GameHelper.createApiClientBuilder() after "
+ "calling setup. You can only get a client builder BEFORE performing setup.";
logError(error);
throw new IllegalStateException(error);
}
GoogleApiClient.Builder builder = new GoogleApiClient.Builder(
mActivity, this, this);
if (0 != (mRequestedClients & CLIENT_GAMES)) {
builder.addApi(Games.API, mGamesApiOptions);
builder.addScope(Games.SCOPE_GAMES);
}
if (0 != (mRequestedClients & CLIENT_PLUS)) {
builder.addApi(Plus.API);
builder.addScope(Plus.SCOPE_PLUS_LOGIN);
}
if (0 != (mRequestedClients & CLIENT_SNAPSHOT)) {
builder.addScope(Drive.SCOPE_APPFOLDER);
builder.addApi(Drive.API);
}
mGoogleApiClientBuilder = builder;
return builder;
}
public void setup(GameHelperListener listener) {
if (mSetupDone) {
String error = "GameHelper: you cannot call GameHelper.setup() more than once!";
logError(error);
throw new IllegalStateException(error);
}
mListener = listener;
debugLog("Setup: requested clients: " + mRequestedClients);
if (mGoogleApiClientBuilder == null) {
// we don't have a builder yet, so create one
createApiClientBuilder();
}
mGoogleApiClient = mGoogleApiClientBuilder.build();
mGoogleApiClientBuilder = null;
mSetupDone = true;
}
public GoogleApiClient getApiClient() {
if (mGoogleApiClient == null) {
throw new IllegalStateException(
"No GoogleApiClient. Did you call setup()?");
}
return mGoogleApiClient;
}
public boolean isSignedIn() {
return mGoogleApiClient != null && mGoogleApiClient.isConnected();
}
public boolean isConnecting() {
return mConnecting;
}
public boolean hasSignInError() {
return mSignInFailureReason != null;
}
public SignInFailureReason getSignInError() {
return mSignInFailureReason;
}
public void setShowErrorDialogs(boolean show) {
mShowErrorDialogs = show;
}
public void onStart(Activity act) {
mActivity = act;
mAppContext = act.getApplicationContext();
debugLog("onStart");
assertConfigured("onStart");
if (mConnectOnStart) {
if (mGoogleApiClient.isConnected()) {
Log.w(TAG,
"GameHelper: client was already connected on onStart()");
} else {
debugLog("Connecting client.");
mConnecting = true;
mGoogleApiClient.connect();
}
} else {
debugLog("Not attempting to connect becase mConnectOnStart=false");
debugLog("Instead, reporting a sign-in failure.");
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
notifyListener(false);
}
}, 1000);
}
}
public void onStop() {
debugLog("onStop");
assertConfigured("onStop");
if (mGoogleApiClient.isConnected()) {
debugLog("Disconnecting client due to onStop");
mGoogleApiClient.disconnect();
} else {
debugLog("Client already disconnected when we got onStop.");
}
mConnecting = false;
mExpectingResolution = false;
// let go of the Activity reference
mActivity = null;
}
public String getInvitationId() {
if (!mGoogleApiClient.isConnected()) {
Log.w(TAG,
"Warning: getInvitationId() should only be called when signed in, "
+ "that is, after getting onSignInSuceeded()");
}
return mInvitation == null ? null : mInvitation.getInvitationId();
}
public Invitation getInvitation() {
if (!mGoogleApiClient.isConnected()) {
Log.w(TAG,
"Warning: getInvitation() should only be called when signed in, "
+ "that is, after getting onSignInSuceeded()");
}
return mInvitation;
}
public boolean hasInvitation() {
return mInvitation != null;
}
public boolean hasTurnBasedMatch() {
return mTurnBasedMatch != null;
}
public boolean hasRequests() {
return mRequests != null;
}
public void clearInvitation() {
mInvitation = null;
}
public void clearTurnBasedMatch() {
mTurnBasedMatch = null;
}
public void clearRequests() {
mRequests = null;
}
public TurnBasedMatch getTurnBasedMatch() {
if (!mGoogleApiClient.isConnected()) {
Log.w(TAG,
"Warning: getTurnBasedMatch() should only be called when signed in, "
+ "that is, after getting onSignInSuceeded()");
}
return mTurnBasedMatch;
}
public ArrayList<GameRequest> getRequests() {
if (!mGoogleApiClient.isConnected()) {
Log.w(TAG, "Warning: getRequests() should only be called "
+ "when signed in, "
+ "that is, after getting onSignInSuceeded()");
}
return mRequests;
}
public void enableDebugLog(boolean enabled) {
mDebugLog = enabled;
if (enabled) {
debugLog("Debug log enabled.");
}
}
#Deprecated
public void enableDebugLog(boolean enabled, String tag) {
Log.w(TAG, "GameHelper.enableDebugLog(boolean,String) is deprecated. "
+ "Use GameHelper.enableDebugLog(boolean)");
enableDebugLog(enabled);
}
public void signOut() {
if (!mGoogleApiClient.isConnected()) {
// nothing to do
debugLog("signOut: was already disconnected, ignoring.");
return;
}
// for Plus, "signing out" means clearing the default account and
// then disconnecting
if (0 != (mRequestedClients & CLIENT_PLUS)) {
debugLog("Clearing default account on PlusClient.");
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
}
// For the games client, signing out means calling signOut and
// disconnecting
if (0 != (mRequestedClients & CLIENT_GAMES)) {
debugLog("Signing out from the Google API Client.");
Games.signOut(mGoogleApiClient);
}
// Ready to disconnect
debugLog("Disconnecting client.");
mConnectOnStart = false;
mConnecting = false;
mGoogleApiClient.disconnect();
}
public void onActivityResult(int requestCode, int responseCode,
Intent intent) {
debugLog("onActivityResult: req="
+ (requestCode == RC_RESOLVE ? "RC_RESOLVE" : String
.valueOf(requestCode)) + ", resp="
+ GameHelperUtils.activityResponseCodeToString(responseCode));
if (requestCode != RC_RESOLVE) {
debugLog("onActivityResult: request code not meant for us. Ignoring.");
return;
}
// no longer expecting a resolution
mExpectingResolution = false;
/* if (!mConnecting) {
debugLog("onActivityResult: ignoring because we are not connecting.");
return;
}*/
if (responseCode == Activity.RESULT_OK) {
// Ready to try to connect again.
debugLog("onAR: Resolution was RESULT_OK, so connecting current client again.");
connect();
} else if (responseCode == GamesActivityResultCodes.RESULT_RECONNECT_REQUIRED) {
debugLog("onAR: Resolution was RECONNECT_REQUIRED, so reconnecting.");
connect();
fireOnReconectRequired();
} else if (responseCode == Activity.RESULT_CANCELED) {
// User cancelled.
debugLog("onAR: Got a cancellation result, so disconnecting.");
mSignInCancelled = true;
mConnectOnStart = false;
mUserInitiatedSignIn = false;
mSignInFailureReason = null; // cancelling is not a failure!
mConnecting = false;
mGoogleApiClient.disconnect();
// increment # of cancellations
int prevCancellations = getSignInCancellations();
int newCancellations = incrementSignInCancellations();
debugLog("onAR: # of cancellations " + prevCancellations + " --> "
+ newCancellations + ", max " + mMaxAutoSignInAttempts);
notifyListener(false);
} else {
// Whatever the problem we were trying to solve, it was not
// solved. So give up and show an error message.
debugLog("onAR: responseCode="
+ GameHelperUtils
.activityResponseCodeToString(responseCode)
+ ", so giving up.");
giveUp(new SignInFailureReason(mConnectionResult.getErrorCode(),
responseCode));
}
}
void notifyListener(boolean success) {
debugLog("Notifying LISTENER of sign-in "
+ (success ? "SUCCESS"
: mSignInFailureReason != null ? "FAILURE (error)"
: "FAILURE (no error)"));
if (mListener != null) {
if (success) {
mListener.onSignInSucceeded();
} else {
mListener.onSignInFailed();
}
}
}
public void beginUserInitiatedSignIn() {
debugLog("beginUserInitiatedSignIn: resetting attempt count.");
resetSignInCancellations();
mSignInCancelled = false;
mConnectOnStart = true;
if (mGoogleApiClient.isConnected()) {
// nothing to do
logWarn("beginUserInitiatedSignIn() called when already connected. "
+ "Calling listener directly to notify of success.");
notifyListener(true);
return;
} else if (mConnecting) {
logWarn("beginUserInitiatedSignIn() called when already connecting. "
+ "Be patient! You can only call this method after you get an "
+ "onSignInSucceeded() or onSignInFailed() callback. Suggestion: disable "
+ "the sign-in button on startup and also when it's clicked, and re-enable "
+ "when you get the callback.");
// ignore call (listener will get a callback when the connection
// process finishes)
return;
}
debugLog("Starting USER-INITIATED sign-in flow.");
mUserInitiatedSignIn = true;
if (mConnectionResult != null) {
debugLog("beginUserInitiatedSignIn: continuing pending sign-in flow.");
mConnecting = true;
resolveConnectionResult();
} else {
// We don't have a pending connection result, so start anew.
debugLog("beginUserInitiatedSignIn: starting new sign-in flow.");
mConnecting = true;
connect();
}
}
void connect() {
if (mGoogleApiClient.isConnected()) {
debugLog("Already connected.");
return;
}
debugLog("Starting connection.");
mConnecting = true;
mInvitation = null;
mTurnBasedMatch = null;
mGoogleApiClient.connect();
}
public void reconnectClient() {
if (!mGoogleApiClient.isConnected()) {
Log.w(TAG, "reconnectClient() called when client is not connected.");
// interpret it as a request to connect
connect();
} else {
debugLog("Reconnecting client.");
mGoogleApiClient.reconnect();
}
}
#Override
public void onConnected(Bundle connectionHint) {
debugLog("onConnected: connected!");
if (connectionHint != null) {
debugLog("onConnected: connection hint provided. Checking for invite.");
Invitation inv = connectionHint
.getParcelable(Multiplayer.EXTRA_INVITATION);
if (inv != null && inv.getInvitationId() != null) {
// retrieve and cache the invitation ID
debugLog("onConnected: connection hint has a room invite!");
mInvitation = inv;
debugLog("Invitation ID: " + mInvitation.getInvitationId());
}
// Do we have any requests pending?
mRequests = Games.Requests
.getGameRequestsFromBundle(connectionHint);
if (!mRequests.isEmpty()) {
// We have requests in onConnected's connectionHint.
debugLog("onConnected: connection hint has " + mRequests.size()
+ " request(s)");
}
debugLog("onConnected: connection hint provided. Checking for TBMP game.");
mTurnBasedMatch = connectionHint
.getParcelable(Multiplayer.EXTRA_TURN_BASED_MATCH);
}
// we're good to go
succeedSignIn();
}
void succeedSignIn() {
debugLog("succeedSignIn");
mSignInFailureReason = null;
mConnectOnStart = true;
mUserInitiatedSignIn = false;
mConnecting = false;
notifyListener(true);
}
private final String GAMEHELPER_SHARED_PREFS = "GAMEHELPER_SHARED_PREFS";
private final String KEY_SIGN_IN_CANCELLATIONS = "KEY_SIGN_IN_CANCELLATIONS";
// Return the number of times the user has cancelled the sign-in flow in the
// life of the app
int getSignInCancellations() {
SharedPreferences sp = mAppContext.getSharedPreferences(
GAMEHELPER_SHARED_PREFS, Context.MODE_PRIVATE);
return sp.getInt(KEY_SIGN_IN_CANCELLATIONS, 0);
}
int incrementSignInCancellations() {
int cancellations = getSignInCancellations();
SharedPreferences.Editor editor = mAppContext.getSharedPreferences(
GAMEHELPER_SHARED_PREFS, Context.MODE_PRIVATE).edit();
editor.putInt(KEY_SIGN_IN_CANCELLATIONS, cancellations + 1);
editor.commit();
return cancellations + 1;
}
void resetSignInCancellations() {
SharedPreferences.Editor editor = mAppContext.getSharedPreferences(
GAMEHELPER_SHARED_PREFS, Context.MODE_PRIVATE).edit();
editor.putInt(KEY_SIGN_IN_CANCELLATIONS, 0);
editor.commit();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// save connection result for later reference
debugLog("onConnectionFailed");
mConnectionResult = result;
debugLog("Connection failure:");
debugLog(" - code: "
+ GameHelperUtils.errorCodeToString(mConnectionResult
.getErrorCode()));
debugLog(" - resolvable: " + mConnectionResult.hasResolution());
debugLog(" - details: " + mConnectionResult.toString());
int cancellations = getSignInCancellations();
boolean shouldResolve = false;
if (mUserInitiatedSignIn) {
debugLog("onConnectionFailed: WILL resolve because user initiated sign-in.");
shouldResolve = true;
} else if (mSignInCancelled) {
debugLog("onConnectionFailed WILL NOT resolve (user already cancelled once).");
shouldResolve = false;
} else if (cancellations < mMaxAutoSignInAttempts) {
debugLog("onConnectionFailed: WILL resolve because we have below the max# of "
+ "attempts, "
+ cancellations
+ " < "
+ mMaxAutoSignInAttempts);
shouldResolve = true;
} else {
shouldResolve = false;
debugLog("onConnectionFailed: Will NOT resolve; not user-initiated and max attempts "
+ "reached: "
+ cancellations
+ " >= "
+ mMaxAutoSignInAttempts);
}
if (!shouldResolve) {
// Fail and wait for the user to want to sign in.
debugLog("onConnectionFailed: since we won't resolve, failing now.");
mConnectionResult = result;
mConnecting = false;
notifyListener(false);
return;
}
debugLog("onConnectionFailed: resolving problem...");
resolveConnectionResult();
}
void resolveConnectionResult() {
// Try to resolve the problem
if (mExpectingResolution) {
debugLog("We're already expecting the result of a previous resolution.");
return;
}
if (mActivity == null) {
debugLog("No need to resolve issue, activity does not exist anymore");
return;
}
debugLog("resolveConnectionResult: trying to resolve result: "
+ mConnectionResult);
if (mConnectionResult.hasResolution()) {
// This problem can be fixed. So let's try to fix it.
debugLog("Result has resolution. Starting it.");
try {
// launch appropriate UI flow (which might, for example, be the
// sign-in flow)
mExpectingResolution = true;
mConnectionResult.startResolutionForResult(mActivity,
RC_RESOLVE);
} catch (SendIntentException e) {
// Try connecting again
debugLog("SendIntentException, so connecting again.");
connect();
}
} else {
// It's not a problem what we can solve, so give up and show an
// error.
debugLog("resolveConnectionResult: result has no resolution. Giving up.");
giveUp(new SignInFailureReason(mConnectionResult.getErrorCode()));
mConnectionResult = null;
}
}
public void disconnect() {
if (mGoogleApiClient.isConnected()) {
debugLog("Disconnecting client.");
mGoogleApiClient.disconnect();
} else {
Log.w(TAG,
"disconnect() called when client was already disconnected.");
}
}
void giveUp(SignInFailureReason reason) {
mConnectOnStart = false;
disconnect();
mSignInFailureReason = reason;
if (reason.mActivityResultCode == GamesActivityResultCodes.RESULT_APP_MISCONFIGURED) {
// print debug info for the developer
GameHelperUtils.printMisconfiguredDebugInfo(mAppContext);
}
showFailureDialog();
mConnecting = false;
notifyListener(false);
}
#Override
public void onConnectionSuspended(int cause) {
debugLog("onConnectionSuspended, cause=" + cause);
disconnect();
mSignInFailureReason = null;
debugLog("Making extraordinary call to onSignInFailed callback");
mConnecting = false;
notifyListener(false);
}
. . .
void debugLog(String message) {
if (mDebugLog) {
Log.d(TAG, message);
}
}
void logWarn(String message) {
Log.w(TAG, "!!! GameHelper WARNING: " + message);
}
void logError(String message) {
Log.e(TAG, "*** GameHelper ERROR: " + message);
}
// Represents the reason for a sign-in failure
public static class SignInFailureReason {
public static final int NO_ACTIVITY_RESULT_CODE = -100;
int mServiceErrorCode = 0;
int mActivityResultCode = NO_ACTIVITY_RESULT_CODE;
public int getServiceErrorCode() {
return mServiceErrorCode;
}
public int getActivityResultCode() {
return mActivityResultCode;
}
public SignInFailureReason(int serviceErrorCode, int activityResultCode) {
mServiceErrorCode = serviceErrorCode;
mActivityResultCode = activityResultCode;
}
public SignInFailureReason(int serviceErrorCode) {
this(serviceErrorCode, NO_ACTIVITY_RESULT_CODE);
}
public void setConnectOnStart(boolean connectOnStart) {
debugLog("Forcing mConnectOnStart=" + connectOnStart);
mConnectOnStart = connectOnStart;
}
}
I've tried to change the score, but there is nothing, I have also checked that the leaderboard is set up correctly.
When I check which languages are available Thai (th)is available butit doesn't read the text
#SuppressLint("NewApi")
private void speak() {
if(tts!=null && tts.isSpeaking()){
tts.stop();
}else{
tts = new TextToSpeech(this, this);
tts.setLanguage(Locale.forLanguageTag("th")); //tts.getAvailableLanguages().;
tts.setSpeechRate(0.7f);
}
}
#Override
public void onInit(int status) {
tts.speak("ซึ่งมีระยะทางส่วนใหญ่เป็น ทางหลวงแผ่นดินหมายเลข (สายบางนา - หาดเล็ก) เป็นเส้นทางคมนาคมหลักเส้นหนึ่งของประเทศไทย ", TextToSpeech.QUEUE_FLUSH, null);
}
Edit your code like this:
#SuppressLint("NewApi")
private void speak() {
if(tts!=null && tts.isSpeaking()) {
tts.stop();
}else{
tts = new TextToSpeech(this, this);
}
}
#Override public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int res = tts.setLanguage("th_TH");
//tts.getAvailableLanguages().;
tts.setSpeechRate(0.7f);
if (res >= TextToSpeech.LANG_AVAILABLE) {
tts.speak("ซึ่งมีระยะทางส่วนใหญ่เป็น ทางหลวงแผ่นดินหมายเลข (สายบางนา - หาดเล็ก) เป็นเส้นทางคมนาคมหลักเส้นหนึ่งของประเทศไทย ", TextToSpeech.QUEUE_FLUSH, null);
}
}
Because TextToSpeech instance is created asynchronously, so you can hear synthesis result when you control your tts after onInit() method was done.
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.
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();
}
}