How to use OnUtteranceProgressListener() with TTS? - java

I want to Toast a message based on the state of TTS.
For this I used OnUtteranceProgressListener() . But I didn't get the result.
How can I achieve this task ?
Code given below is used to initialize TTS class.
textToSpeech=new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
//Check if initialisation is successful
if(i==TextToSpeech.SUCCESS)
{
//set Language
int result=textToSpeech.setLanguage(Locale.ENGLISH);
//Check if language is set successfully or not.
if(result==TextToSpeech.LANG_NOT_SUPPORTED||result==TextToSpeech.LANG_MISSING_DATA)
{
Toast.makeText(MainActivity.this, "Language not supported", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "Welcome", Toast.LENGTH_SHORT).show();
textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String s) {
Toast.makeText(MainActivity.this, "Started", Toast.LENGTH_SHORT).show();
}
#Override
public void onDone(String s) {
Toast.makeText(MainActivity.this,"Done",Toast.LENGTH_SHORT).show();
}
#Override
public void onError(String s) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
});
}
}
else{
Toast.makeText(MainActivity.this, "Initialisation failed", Toast.LENGTH_SHORT).show();
}
}
});
Code given below is used to trigger the event
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
speak();
}
});
speak() function definition:
private void speak() {
String text="Good Morning";
float pitch=(float)seekBarPitch.getProgress()/50;
float speed=(float)seekBarSpeed.getProgress()/50;
textToSpeech.setPitch(pitch);
textToSpeech.setSpeechRate(speed);
textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null,"UTTERANCE_ID");
}

Toast message do not work in background thread.
So we must run it on UI Thread by using runOnUIThread();

Related

Huawei Ads, onAdClosed is not called

I'm trying to integrate the interstitial ad from Huawei Ads, when I click on (X) or back button to close the ad, for some reason the Toast inside onAdClosed method is not showing.
huaweiInterstitialAd = new InterstitialAd(MainActivity.this);
huaweiInterstitialAd.setAdId("teste9ih9j0rc3");
private void showHuaweiInterstitial() {
if (huaweiInterstitialAd != null && huaweiInterstitialAd.isLoaded()) {
huaweiInterstitialAd.show(MainActivity.this);
}
}
public void loadHuaweiInterstitialAd() {
huaweiInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
showHuaweiInterstitial();
}
#Override
public void onAdFailed(int errorCode) {
Log.d(TAG, "Ad load failed with error code: " + errorCode);
}
#Override
public void onAdLeave() {
super.onAdLeave();
Log.d(TAG, "onAdLeave");
}
#Override
public void onAdClosed() {
super.onAdClosed();
Toast.makeText(MainActivity.this, "Ad Closed", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdClicked() {
Log.d(TAG, "onAdClicked");
super.onAdClicked();
}
#Override
public void onAdOpened() {
Log.d(TAG, "onAdOpened");
super.onAdOpened();
}
});
AdParam adParam = new AdParam.Builder().build();
huaweiInterstitialAd.loadAd(adParam);
}
The problem only occurs if you use:
implementation 'com.huawei.hms:ads:3.4.46.300'
But everything works fine with :
implementation 'com.huawei.hms:ads-lite:13.4.46.300'

Which function returns the recorded audio when I use SpeechRecognizer in android studio?

I am building a custom keyboard app(in android studio) in which I added a microphone key. I wanted to convert the recorded speech to text so I used speechrecognizer. But I also want the recorded audio. I want that my keyboard app when records the audio in chatting applications like whatsapp, it should send that audio as the message. Could somebody help me how to get the recorded audio when i use speechrecognizer. I need to use speechrecognizer only as i need it for other purpose.
(p.s: my app do not have any activity)
This is the code for recording speech and converting to text.
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, "com.example.keyboard");
SpeechRecognizer recognizer = SpeechRecognizer.createSpeechRecognizer(this.getApplicationContext());
RecognitionListener listener = new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
Toast.makeText(EDMTKeyboard.this, "Recording Started", Toast.LENGTH_SHORT).show();
}
#Override
public void onBeginningOfSpeech() {
Toast.makeText(EDMTKeyboard.this, "Recording Started", Toast.LENGTH_SHORT).show();
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int error) {
System.err.println("Error listening for speech: " + error);
Toast.makeText(EDMTKeyboard.this, "ERROR-"+error, Toast.LENGTH_SHORT).show();
}
#Override
public void onResults(Bundle results) {
Bundle bundle = intent.getExtras();
ArrayList<String> voiceResults = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (voiceResults == null) {
System.out.println("No voice results");
} else {
System.out.println("Printing matches: ");
for (String match : voiceResults) {
Toast.makeText(EDMTKeyboard.this, match, Toast.LENGTH_SHORT).show();
ic.commitText(match,match.length());
str = str + match;
I=I+match.length()+1;
//System.out.println(match);
}
}
}
#Override
public void onPartialResults(Bundle partialResults) {
}
#Override
public void onEvent(int eventType, Bundle params) {
}
};
recognizer.setRecognitionListener(listener);
recognizer.startListening(intent);
I checked the questions similar to this in stackoverflow, but the answers given were not working at present(may be the android studio had removed those functions).

how to make toast of current selected text from this array adaptor

i am getting problem to copy or print toast message from this array adaptor. I am using swipe cardview library and i want to copy current displayed text from cardview when i click on copy button. I tried to copy text but it is copying xml layout text not that text which i added to list.
This is my code
fillingcontainer = findViewById(R.id.frame);
textView = findViewById(R.id.hellotext);
copy=findViewById(R.id.copy);
button=findViewById(R.id.download);
layout=findViewById(R.id.lalla);
al = new ArrayList<String>();
al = new ArrayList<String>();
al.add("Ni");
al.add("Ro");
al.add("Ka");
al.add("Nar");
random= new Random();
lins= Arrays.asList(getResources().getStringArray(R.array.coorss));
arrayAdapter = new ArrayAdapter<String>(this, R.layout.itemas, R.id.hellotext, al);
fillingcontainer.setAdapter(arrayAdapter);
fillingcontainer.getSelectedView().setBackgroundColor(Color.RED);
copy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s= textView.getText().toString();
Toast.makeText(MainActivity.this, ""+s, Toast.LENGTH_SHORT).show();
}
});
fillingcontainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
al.remove(0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object o) {
Toast.makeText(MainActivity.this, "Left!", Toast.LENGTH_SHORT).show();
if (i%5==0) {
Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
}
String s =textView.getText().toString();
}
#Override
public void onRightCardExit(Object o) {
Toast.makeText(MainActivity.this, "Right!", Toast.LENGTH_SHORT).show();
i++;
if (i%5==0) {
Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onAdapterAboutToEmpty(int i) {
al.add("NO more text ".concat(String.valueOf(i)));
arrayAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
}
#Override
public void onScroll(float v) {
}
});
fillingcontainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
Toast.makeText(MainActivity.this, "clciekd", Toast.LENGTH_SHORT).show();
}
});
}

Show a progress Bar when Rewarded video Ads is loading

I want to use Rewarded video ads (Admob) but I want to show a progress bar while the video ads is loading
I already try to did it with async task just to see if the video will load but it didn't work
#SuppressLint("StaticFieldLeak")
public class videoAd extends AsyncTask<Void, Void, Void> {
#Override
protected void doInBackground(Void... voids) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
}
});
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if (mRewardedVideoAd.isLoaded()){
Toast.makeText(SetFullWallpaper.this, "Video loaded", Toast.LENGTH_SHORT).show();
mRewardedVideoAd.show();
}
}
}
Now I want to load a progress bar if the video is not loaded yet
Thank you
This is how I did it:
I had a button, which when clicked showed the ad, so I had a boolean variable which tracked whether the button has been clicked:
boolean buttonClicked = false
These lines were in my onCreate function:
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(getContext());
rewardedVideoAdListener = new RewardedVideoAdListener() {
#Override
public void onRewardedVideoAdLoaded() {
if(buttonClicked) {
showAd();
}
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
if(buttonClicked) {
progressBar.setVisibility(View.INVISIBLE);
Toast toast = Toast.makeText(getContext(), "Please try again later", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onRewardedVideoCompleted() {
}
};
mRewardedVideoAd.setRewardedVideoAdListener(rewardedVideoAdListener);
loadRewardedVideoAd();
pointsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showAd();
}
});
This was my showAd function:
public void showAd(){
if (mRewardedVideoAd.isLoaded()) {
progressBar.setVisibility(View.GONE);
mRewardedVideoAd.show();
buttonClicked = false;
} else {
loadRewardedVideoAd();
progressBar.setVisibility(View.VISIBLE);
buttonClicked = true;
}
}
How this works is, the app tries to load the ad in the background by calling the loadRewaredVideoAd() function when the activity/fragment is created. Then when the user clicks the button,showAd() function is called and one of two things happen:
1) If the ad was successfully loaded, it shows the ad.
2) If not, it calls loadRewardedVideoAd() again and shows a progressbar this time. It also sets buttonClicked to true. Then if the ad loads, the onRewardedVideoAdLoaded() function is called which calls showAd() again and this time the 1st option happens.
If the ad didn't load this time as well, then onRewardedVideoAdFailedToLoad(int i)is called and it shows a toast saying the user to try again later.
add OnProgressUpdate() in your class that extends AsyncTask and add progress dialog in this.
I am placing an admob video, which is executed when you enter the activity. In my case, I put an executable loop to start the video when it is already loaded.
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}else{
loadRewardedVideoAd();
}
This is part of all my code
private boolean started = false;
private Handler handler = new Handler();
private void initializeAdMob() {
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
}
private void loadRewardedVideoAd() {
if (!mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.loadAd(getString(R.string.id_block_activity), new AdRequest.Builder().build());
}
}
private void showRewardedVideoAd() {
if (BaseInteractor.isNetworkAvailable(this)) {
showProgressBar(true);
start();
}
}
private Runnable runnable = new Runnable() {
#Override
public void run() {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}else{
loadRewardedVideoAd();
}
if (started) {
start();
}
}
};
public void stop() {
started = false;
handler.removeCallbacks(runnable);
}
public void start() {
started = true;
handler.postDelayed(runnable, 2000);
}
finally I stop the runnable in
#Override
public void onRewardedVideoAdOpened() {
showProgressBar(false);
stop();
}
I hope this helps you.

Toasts in if and else are executed when else condition is true. Code first gives "signup successful" then it gives "user already exists"

On creating a new account, this code first gives "signup successful" then it gives "user already exists". Everything else is working fine.
Help me out with this. Thank you very much for your time and assistance in this matter.
also tried:
dataSnapshot.child(edtRoll.getText().toString())!=null
but it make the situation more worse, it always shows "user doesn't exist".
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (edtRoll.getText().toString().trim().length()!= 9)
Toast.makeText(SignUp.this, "Roll No. must have 9 characters!", Toast.LENGTH_SHORT).show();
else if (edtName.getText().toString().trim().length() < 3)
Toast.makeText(SignUp.this, "Name is too short!", Toast.LENGTH_SHORT).show();
else if (edtPassword.getText().toString().trim().length() < 8)
Toast.makeText(SignUp.this, "Password must have atleast 8 characters!", Toast.LENGTH_SHORT).show();
else if(!(edtPassword.getText().toString()).equals(edtConfirmPassword.getText().toString()))
Toast.makeText(SignUp.this, "Passwords do not match!", Toast.LENGTH_SHORT).show();
else {
final ProgressDialog mDialog = new ProgressDialog(SignUp.this);
mDialog.setMessage("Please Wait...");
mDialog.show();
table_user.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Check if userRoll already exist
if (dataSnapshot.child(edtRoll.getText().toString()).exists()) {
mDialog.dismiss();
Toast.makeText(SignUp.this, "User already registered!", Toast.LENGTH_SHORT).show();
} else {
mDialog.dismiss();
User user = new User(edtName.getText().toString(), edtPassword.getText().toString());
table_user.child(edtRoll.getText().toString()).setValue(user);
Toast.makeText(SignUp.this, "Sign up Successfull!", Toast.LENGTH_SHORT).show();
finish();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
});
Probably this is happened because whenever the button is clicked and user is in sign up state which giving "signup successful" , you're re-registering the listener for the data change:
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (...) {
...
} else {
table_user.addValueEventListener(new ValueEventListener() {
...
}
}
}
});
Hence you're receiving the "signup successful" then "user already exists" message.
You need to initialize the data change listener outside the click button method. Something like this:
final ProgressDialog mDialog;
private void initDataChangeListener() {
table_user.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
...
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Then call the initDataChangeListener before adding the click listener:
initDataChangeListener();
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (...) {
...
} else {
if(mDialog == null) mDialog = new ProgressDialog(SignUp.this);
mDialog.setMessage("Please Wait...");
mDialog.show();
// no need to handle the data, because it's already handled by the data change listener.
}
}
});

Categories