private TextToSpeech tts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
tts = new TextToSpeech(this,(OnInitListener) clickball);
}
OnClickListener clickball=new OnClickListener() {
#Override
public void onClick(View v) {
score=scorenumber.nextInt(8);
ballid=v.getId();
if(score==4)
{
playgame(ballid,Integer.toString(score));
dynamic_image.setBackgroundDrawable(getResources().getDrawable(R.drawable.four_01));
dynamic_image.setVisibility(0x000000);
disablelayout();
timerfunc1(dynamic_image,R.drawable.four_02);
tts.setLanguage(Locale.US);
tts.speak("Four", TextToSpeech.QUEUE_FLUSH, null);
dynamic_image.postDelayed(new Runnable(){
#Override
public void run() {
dynamic_image.setBackgroundDrawable(getResources().getDrawable(R.drawable.score4));
dynamic_image.setVisibility(0x000000);
timerfunc(dynamic_image);
}
}, 2200);
enablelayout4();
}
}
Given above is my source code.but it is throwing classcast exception when it runs..i want to convert the text "Four" to speech when the score is 4.plz anybody help me...i know given below line of code throwing the exception.but i dnt know hot to solve it..
tts = new TextToSpeech(this,(OnInitListener) clickball);
i got the answer...i gave clicklistener name in
tts = new TextToSpeech(this,(OnInitListener) clickball);
actuallly i had to give the OnInitListener name there.i had changed the code like this..
fisrt implement TextToSpeech.OnInitListener
and added its unimplemented method(OnInit).
private TextToSpeech tts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
tts = new TextToSpeech(this,this);
OnClickListener clickball=new OnClickListener() {
#Override
public void onClick(View v) {
score=scorenumber.nextInt(8);
ballid=v.getId();
if (totalovers==0)
{
gameover();
return;
}
if(score==4)
{
playgame(ballid,Integer.toString(score));
dynamic_image.setBackgroundDrawable(getResources().getDrawable(R.drawable.four_01));
dynamic_image.setVisibility(0x000000);
disablelayout();
timerfunc1(dynamic_image,R.drawable.four_02);
currentScore ="FOUR";
tts.setLanguage(Locale.US);
tts.speak(currentScore, TextToSpeech.QUEUE_FLUSH, null);
dynamic_image.postDelayed(new Runnable(){
#Override
public void run() {
dynamic_image.setBackgroundDrawable(getResources().getDrawable(R.drawable.score4));
dynamic_image.setVisibility(0x000000);
timerfunc(dynamic_image);
}
}, 2000);
enablelayout4();
}
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
}
this solved my problem...
Related
This is a test activity when the button is pressed the textToSpeech works just fine, but it wont work when the function playString() is called, playString() is being called from the onCreate() of this TestActivity.
public class TestActivity extends Activity {
TextToSpeech textToSpeech;
EditText editText;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
editText=(EditText)findViewById(R.id.editText);
button=(Button)findViewById(R.id.button);
textToSpeech=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.UK);
}
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String sentence = "Testing String";
textToSpeech.speak(sentence, TextToSpeech.QUEUE_FLUSH, null);
}
});
playString();
}
public void playString(){
String sentence = "Testing String";
textToSpeech.speak(sentence, TextToSpeech.QUEUE_FLUSH, null);
}
public void onPause(){
if(textToSpeech !=null){
textToSpeech.stop();
textToSpeech.shutdown();
}
super.onPause();
}
}
From documentation:
TextToSpeech instance can only be used to synthesize text once it has completed its initialization.
Initialization may take long time (on my device it's take ~30 seconds), so you can't use handler with some random delay.
Instead, you can place playString() in onInit block right after textToSpeech.setLanguage(Locale.UK);, so string will be played when it can be played.
Please use below code in oncreate method to call the texttospeech:
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.UK);
}
}
});
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100ms
String sentence = "Testing String";
textToSpeech.speak(sentence, TextToSpeech.QUEUE_FLUSH, null);
}
}, 500);
This is my code to perform click automatically when the activity opens but it is not working
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notify);
editspeak = (EditText) findViewById(R.id.editspeak);
btspeak=(Button)findViewById(R.id.bt);
// speakout();
// mydb = new DBhandler(this);
SharedPreferences preferences=getSharedPreferences(PREFS,0);
String name=preferences.getString("NAME",null);
editspeak.setText(name);
t1=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
t1.setLanguage(Locale.US);
}
}
});
btspeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = editspeak.getText().toString();
t1.speak(text, TextToSpeech.QUEUE_FLUSH, null);
// bt.setPressed(false);
// bt.invalidate();
}
});
btspeak.performClick();
The problem here is that you call speak before the TextToSpeech is fully initialised (you can add a few logs to check this). To fix this behaviour you can use performClick in this way to delay the call until everything else is finished initialising:
btspeak.post(new Runnable() {
#Override
public void run() {
btspeak.performClick();
}
});
I am using this kind of text to speech in one of my class in my app(Code edited to show outlook & exact requirement.). I will show some content on my view & if we click the button , I want to play the sound that is by using this texttospeech engine... But for First time it is not playing the sound. From the next click onwards the TEXTTOSPEECH engine is working nicely
Iwant to know how to overcome this issue....
public class LearnActivity extends Activity implements OnClickListener, OnInitListener {
AudioManager audioManager;
float volume;
TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_learn);
textToSpeech = new TextToSpeech(this, this);
textToSpeech.setLanguage(Locale.US);
textToSpeech.setSpeechRate(0.95f);
method();
}
public void method(){
bt.setonClickListener(new onClickListener(){
public void onClick(View v){
playSound(datasource.getItemSound);
}
});
}
public void playSound(String sound){
textToSpeech.speak(sound,TextToSpeech.QUEUE_FLUSH,null);
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
}
NOTE:- This also meet my Requirement, How to play sound from TEXTTOSPEECH engine directly without using any onClicks etc.,... because I also wants to play a startup sound that too with Android's Text-To-Speech engine only...
That's because you are clicking the button before the engine is ready.
You have to check if the TTS engine has successfully initialized on your onInit() method and enable/disable the play button accordingly.
Assuming that bt in your code is some sort of View that has setEnabled(boolean) method:
#Override
public void onInit(int status) {
bt.setEnabled(status == TextToSpeech.SUCCESS);
}
You always have to assume that the engine has not been initialized and hence keep your play button disabled by default.
I used RXJava to make a class that solves this problem. If your TTS engine is not ready when you want to use the speak method it will wait for the engine to get ready and then speaks the given string.
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.util.Pair;
import android.widget.Toast;
import java.util.Locale;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
public class Pronunciation {
private TextToSpeech textToSpeech;
private int languageResult;
private boolean noError;
private final String errorMessage="Something went wrong with your text to speech engine";
private PublishSubject<Boolean> engineIsReady=PublishSubject.create();
private PublishSubject<Pair<String,Integer>> speakObservable=PublishSubject.create();
private CompositeDisposable compositeDisposable=new CompositeDisposable();
public Pronunciation(Context context) {
textToSpeech=new TextToSpeech(context, status -> {
if (status!=TextToSpeech.ERROR){
languageResult= textToSpeech.setLanguage(Locale.ENGLISH);
engineIsReady.onNext(true);
} else {
Toast.makeText(context,errorMessage
,Toast.LENGTH_LONG).show();
}
});
if (languageResult==TextToSpeech.LANG_MISSING_DATA||languageResult== TextToSpeech.LANG_NOT_SUPPORTED){
noError =false;
Toast.makeText(context,errorMessage
,Toast.LENGTH_LONG).show();
}else { noError =true;}
compositeDisposable.add( Observable.combineLatest(speakObservable, engineIsReady,
(stringIntegerPair, aBoolean) -> stringIntegerPair)
.subscribeOn(Schedulers.io())
.subscribe(pair->{
if (noError)
textToSpeech.speak( (pair).first
,(pair).second,null,null);
}));
}
public void speak(String text,int queueMode){
speakObservable.onNext(new Pair<>(text,queueMode));
}
public void stop(){
if (textToSpeech!=null){
textToSpeech.stop();
textToSpeech.shutdown();
}
compositeDisposable.clear();
}
}
first add RxJava dependency in your Gradle file
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
Then create an instance of this class in the onCreate method of your activity or fragment.Now you can pass the string and queue mode to the speak method.
pronunciation.speak("Hi", TextToSpeech.QUEUE_FLUSH));
Don't forget to call the stop method in onDestroy or onDetach to avoid memory leak
#Override
public void onDetach() {
super.onDetach();
pronunciation.stop();
}
you should write your program ...
public class MainActivity extends Activity implements TextToSpeech.OnInitListener, OnUtteranceCompletedListener {
TextToSpeech t1;
protected void onCreate(Bundle savedInstanceState) {
t1=new TextToSpeech(MainActivity.this, MainActivity.this);
}/////on creat
protected void onDestroy() {
if(t1!=null) {
t1.stop();
t1.shutdown();
t1=null;
}
super.onDestroy();
}
public void onInit(int arg0) {
t1.setOnUtteranceCompletedListener(this);
}
}//mainactivity
Add this command when button is clicked or everywhere you want to speak text.
t1.speak(text, TextToSpeech.QUEUE_FLUSH, null);
Just Put Delay For 5 Second And It's Working without any button Click
public class Final_Text_To_Speech_Activity extends AppCompatActivity implements TextToSpeech.OnInitListener {
private TextToSpeech tts; // For Text to Speech
CardView ScanProduct, SearchProduct;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
init();
// Just Put Delay For 5 Second And It's Working without any button Click
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
SpeakOutOnce("Welcome to Text To Speech Application");
}
}, 5000);
}
#Override
protected void onResume() {
super.onResume();
}
public void init() {
ScanProduct = (CardView) findViewById(R.id.scan_product);
SearchProduct = (CardView) findViewById(R.id.search_product);
// Search On Button Click
ScanProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut("You have Just pressed Scan Option");
}
});
SearchProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut("You have Just pressed Search Option ");
}
});
}
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#Override
public void onInit(int status) {
int result = tts.setLanguage(Locale.US);
if (status == TextToSpeech.SUCCESS) {
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
} else {
speakOut("");
}
} else if (status == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...",
Toast.LENGTH_LONG).show();
}
}
private void speakOut(String text) {
tts.setPitch(1.0f); //Normal Pitch
tts.setSpeechRate(0.7f); // 1.0 is Normal speech Rate
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
private void SpeakOutOnce(String text) {
if (tts != null) {
tts.setPitch(1.0f); //Normal Pitch
tts.setSpeechRate(0.7f); // 1.0 is Normal speech Rate
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
I need to toast the stopwatch's value
ie.,time taken between start and stop
If i click the stop button it should toast that time duration.
How to do this?
Here i have tried some code
chrono_meter.java
public class Chrono_meter extends Activity {
Chronometer chr;
Button btn_stop_travel;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.chronometer_layout);
chr = (Chronometer)findViewById(R.id.chronometer1);
chr.start();
btn_stop_travel = (Button)findViewById(R.id.btn_stop_inspection);
btn_stop_travel.setOnClickListener(mStopListener);
}
View.OnClickListener mStopListener = new OnClickListener() {
public void onClick(View v) {
chr.stop();
}
};
}
Try this
View.OnClickListener mStopListener = new OnClickListener() {
public void onClick(View v) {
chr.stop();
Toast.makeText(Chrono_meter.this, chr.getText(), Toast.LENGTH_LONG).show() ;
}
};
I'm using the TextToSpeech API in my code and it doesn't work when I try to call .speak() function from OnStart(), however it works when I call it from a button onClickListener(). Any idea why? Thank you.
public class TtsDemoActivity extends Activity {
private TextToSpeech mTts;
private OnClickListener buttonListener = new View.OnClickListener() {
#Override
public void onClick(View arg0) {
PlaySound();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ttsdemo);
// Initialize Text To speech
mTts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int arg0) {
// TODO Auto-generated method stub
}
});
Button myButton = (Button)findViewById(R.id.buttontts1);
myButton.setOnClickListener(buttonListener);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
PlaySound();
}
protected void PlaySound()
{
String word = "Hello world";
mTts.speak(word, TextToSpeech.QUEUE_FLUSH, null);
}
You must wait until the TTS subsystem signals that it is ready: if it isn't ready when onStart is called, it will fail. If you are trying to speak as soon as it is ready call PlaySound from inside the OnInitListener:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ttsdemo);
// Initialize Text To speech
mTts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int arg0) {
if(arg0 == TextToSpeech.SUCCESS) PlaySound();
}
});
Button myButton = (Button)findViewById(R.id.buttontts1);
myButton.setOnClickListener(buttonListener);
}
Maybe I am blind, but in your onStart method, you aren't ever calling
PlaySound()
Like you are in
#Override
public void onClick(View arg0) {
PlaySound();
}