Converting text to speech - android

I am using the following code. Its working fine except a problem that i have list of text to converted as speech. But its only converting last line as a speech. Here is my code where I am putting data in listview and trying to convert it into speech:
public class TextSpeech extends ListActivity implements
TextToSpeech.OnInitListener {
/** Called when the activity is first created. */
private TextToSpeech tts;
private TextView txtText;
private List<Message> mess;
List<String> titless;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.speach);
tts = new TextToSpeech(this, this);
BaseFeedParser parser = new BaseFeedParser();
mess = parser.parse();
titless = new ArrayList<String>(mess.size());
speakOut();
}
#SuppressLint("NewApi")
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
#SuppressLint("NewApi")
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
public void speakOut() {
for (Message msg : mess){
titless.add(msg.getTitle());
tts.speak(msg.getTitle(), TextToSpeech.QUEUE_FLUSH, null);
}
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(this, R.layout.row,titless);
this.setListAdapter(adapter);
}
}

You had used TextToSpeech.QUEUE_FLUSH just changed it to TextToSpeech.QUEUE_ADD .According to your requirement you want TTS to read one by one.

Related

Multiple Instances for TextToSpeech

I need to speak multiple language. I created an array for TextToSpeech.
private TextToSpeech[] mTextSpeechs_;
mTextSpeechs_ = new TextToSpeech[5];
mTextSpeechs_[0] = new TextToSpeech(this, new TextToSpeech.OnInitListener()
{
#Override
public void onInit(int status)
{
mTextSpeechs_[0].setLanguage(Locale.CHINESE);
mTextSpeechs_[0].speak(getString(R.string.string_main_chineseready), TextToSpeech.QUEUE_FLUSH, null,"Display");
}
});
mTextSpeechs_[1] = new TextToSpeech(this, new TextToSpeech.OnInitListener()
{
#Override
public void onInit(int status)
{
mTextSpeechs_[1].setLanguage(Locale.forLanguageTag("yue-HK"));
mTextSpeechs_[1].speak(getString(R.string.string_main_hongkong), TextToSpeech.QUEUE_FLUSH, null,"Display");
}
});
mTextSpeechs_[2] = new TextToSpeech(this, new TextToSpeech.OnInitListener()
{
#Override
public void onInit(int status)
{
mTextSpeechs_[2].setLanguage(Locale.JAPAN);
mTextSpeechs_[2].speak(getString(R.string.string_main_japan), TextToSpeech.QUEUE_FLUSH, null,"Display");
}
});
mTextSpeechs_[3] = new TextToSpeech(this, new TextToSpeech.OnInitListener()
{
#Override
public void onInit(int status)
{
mTextSpeechs_[3].setLanguage(Locale.KOREA);
mTextSpeechs_[3].speak(getString(R.string.string_main_korea), TextToSpeech.QUEUE_FLUSH, null,"Display");
}
});
mTextSpeechs_[4] = new TextToSpeech(this, new TextToSpeech.OnInitListener()
{
#Override
public void onInit(int status)
{
mTextSpeechs_[4].setLanguage(Locale.ENGLISH);
mTextSpeechs_[4].speak(getString(R.string.string_main_english), TextToSpeech.QUEUE_FLUSH, null,"Display");
}
});
....
//type 0 flush
//type 1 add
public void speakMultiLanguage(String text, int type,int langidx)
{
if( type == 0 )
mTextSpeechs_[langidx_].speak(text, TextToSpeech.QUEUE_FLUSH, null,"Display");
else if( type == 1)
mTextSpeechs_[langidx_].speak(text, TextToSpeech.QUEUE_ADD, null,"Display");
}
Now, When I call speakMultiLanguage function to speak specified language, it will delay about 5 seconds to speak. If the last language is same, it will not delay. Does anyone give me a solution to solve the delay?
I wasn't testing your particular case of multiple usage of TTS in array. But for me it looks none productive, especially memory and resources using.
In my case I initialise only one TTS object in onCreate() method of My Activity. And when I need to change languge to another, I'll use tts.setLanguge(Locale).
In my case and with my virtual device this solution working immediately.
initialise:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS){
tts.setLanguage(Locale.ENGLISH);
}else{
Log.e(TAG, "TTS fault");
}
}
});
//....
}
Change:
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void prepareTTS(Locale newLocale){
if (!tts.getVoice().getLocale().getISO3Language().equals(newLocale.getISO3Language())) {
tts.setLanguage(newLocale);
Log.d(TAG, "ChangeTo: " + newLocale.getISO3Language());
}else{
Log.d(TAG, "The same");
}
}
speech:
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void ttsSpeak21(String text){
String utteranceId = this.hashCode() + "";
int result = tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId);
if (result == TextToSpeech.ERROR){
Log.d(TAG, "Can't say");
}else {
Log.d(TAG, lang + "speaking!");
}
}
free resources:
#Override
protected void onDestroy() {
if (tts != null){
tts.stop();
tts.shutdown();
}
super.onDestroy();
}

How can I get Text To Speech to read a foreign language?

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.

What am I misunderstanding regarding Android TTS onInitListener?

I have a class meant to transcribe text to audio files. I want to reuse the class and the TTS engine to speed things up:
public class TtsToFile implements TextToSpeech.OnInitListener {
private TextToSpeech mTts;
private boolean initDone = false;
public TtsToFile() {
mTts = new TextToSpeech(Globals.context, this); // context, listener
while (!initDone) try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
public void transcribe(String speech, String fileOutPath) {
HashMap<String, String> myHashRender = new HashMap();
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, speech);
mTts.synthesizeToFile(speech, myHashRender, fileOutPath);
while (mTts.isSpeaking()) try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
mTts.stop();
return;
}
#Override
public void onInit(int status) {
initDone = true;
return;
}
public void finish() {
mTts.shutdown();
return;
}
}
I call the class like so:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Globals.context = this;
Log.d("a", "a");
TtsToFile ttf = new TtsToFile();
Log.d("a", "b");
ttf.transcribe("hello world", new File(Globals.sdDir, "test.wav").getAbsolutePath());
Log.d("a", "c");
ttf.finish();
Log.d("a", "d");
finish();
}
Yet in LogCat, only "a" is being printed. What am I misunderstanding here? It looks like the class never finishes instantiating and just keeps sleeping. It never reads initDone as true... I think. LogCat shows no crash.

Speak failed: not bound to TTS Engine

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.

Text to speech-not speaking out

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();
}
}

Categories

Resources