Wednesday, July 31, 2013

Text to speech converter

Welcome Learners World of android.

Switching to new tutorial which converts text entered to audio stream.
This application will be helpful for English learners and good pronunciation practicing. Also for those dumb and blind people where learning is simple task.

Step 1 : Create xml file

Create a anew android application. In the xml, Create edit text field and a button to convert text entered in edittext to speech.



Step 2: Get the text entered

 In java class, get the entered text in a string.

EditText enteredText = (EditText)findViewById(R.id.enter);
String words = enteredText.getText().toString();

 Step 3: Create speech method.

Create a speech method and call it in onClick of button. Pass the string "words" obtained in step 2 to it.

 Step 4: Implement TTS within the class

You also need to implement one more interface, so alter your class declaration outline to add “OnInitListener” as in the following example:

public class SpeakingAndroid extends Activity implements OnClickListener, OnInitListener

 Step 5: Check for TTS data 

 Your app needs to check that the user has the data necessary for the TTS function before you call its methods. Declare and instantiate the following instance variable at the top of your Activity class declaration, before the “onCreate” method

private int MY_DATA_CHECK_CODE = 0;
 
 
Also create an intent to keep checking users data in on create method 
 
Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
 
Create an TTS instance 
 
private TextToSpeech myTTS;
 

Implementing onActivityResult

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == MY_DATA_CHECK_CODE) {
        if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
            myTTS = new TextToSpeech(this, this);
        }
        else {
            Intent installTTSIntent = new Intent();
            installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
            startActivity(installTTSIntent);
        }
        }
}
 

Step 6: Create the onInit method

@Override
    public void onInit(int status) {
        if(status == TextToSpeech.SUCCESS){
             if(myTTS.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE)
                 myTTS.setLanguage(Locale.US);
        }
        else if(status == TextToSpeech.ERROR)
            Toast.makeText(this, "Error while loading", Toast.LENGTH_SHORT).show();
    }

Step 7: Add speak method to function created in step3

In your method created in step 3, add this line of code :

myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
 

Step 8: Dont forget to release the sources you used.

myTTS.shutdown();

 NOTE : Dont use this code if you want user to make it speak more than once.

 

 
 
 




 




No comments:

Post a Comment